简体   繁体   English

结合枚举类与策略模式进行模块化设计

[英]Combining Enum Classes with Strategy Pattern for Modular Design

I am a biologist who is trying to improve my dated knowledge of Java and OOP. 我是一位生物学家,他正在努力提高我过时的Java和OOP知识。 I am going through the exercise of writing a game to practice good software design and modularity (why make something fun?). 我正在通过编写游戏来练习良好的软件设计和模块化(为什么要有趣吗?)。

The idea is like Risk but with international banking. 这个想法就像风险,但具有国际银行业务。 Each bank deals with different currencies; 每个银行使用不同的货币; each currency uses different denominations. 每种货币使用不同的面额。 The banks all offer the same functions (balance, withdraw, deposit, exchange) and so would do well with an interface. 所有的银行都提供相同的功能(余额,取款,存款,兑换),因此使用界面会很好。 A currency can also be well described using an Enum representing each denomination and its value. 也可以使用代表每种面额及其价值的枚举来很好地描述一种货币。

This is my very simple example. 这是我非常简单的示例。 I can create new Country() objects for each county in the game. 我可以为游戏中的每个县创建新的Country()对象。

1) Am I forced to manually specify every single country with its respective currency? 1)我是否被迫手动指定每个国家及其货币? Eg: 例如:

Country Canada = new Country(CANCurrency);

This seems rather clunky and there must be a better way to do this. 这似乎很笨拙,必须有更好的方法来做到这一点。

2) From a class using County(), how can I directly access its (indirectly contained) Enum values? 2)从使用County()的类中,如何直接访问其(间接包含的)Enum值?

Each country looks like this: 每个国家如下所示:

public class Country {

    private final String name;
    private ICurrency currency;

    public Country(String name, ICurrency currency) {
        this.name = name;
        this.currency = currency;
    }

    // How do I access the specific Enum constants here?

}

This is my Banking interface: 这是我的银行业务界面:

public interface IBank {
    // Standard banking methods.
    public void deposit(int amount);
    public void withdraw(int amount);
    public int balance();
    public int exchange (Currency demandType, int demand, Currency offerType, int offer);
}

Each country's Currency will largely have similar code, except for the denominations. 除面额外,每个国家/地区的货币都将具有相似的代码。

public interface ICurrency {
    public Currency getCurrency();
    // Maybe some more helper methods here.
}

This is the Currency for Canada: 这是加拿大的货币:

public enum CANCurrency interface ICurrency {
    LOONIE(1), TWONIE(2), FIVE(5); // etc....
}

and the currency for USA: 和美国的货币:

public enum USACurrency interface ICurrency {
    ONE(1), FIVE(5), TEN(10); // etc....
}

You can use enums, even singleton enums, to implement strategies. 您可以使用枚举,甚至单例枚举来实现策略。 In fact that is the best way IMHO. 其实这是恕我直言的最好方法。 It is usually best to ensure that your enums are immutable and stateless, but they are not required to be. 通常最好确保您的枚举是不变的和无状态的,但不是必须如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM