【发布时间】:2016-08-24 17:20:18
【问题描述】:
我有两种类型的交易: - 收入 - 费用
class Transaction {
final public static int IN = 0x1, OUT = 0x2;
final private int type;
Transaction(int type)
{
this.type = type;
}
public int getType() {
return type;
}
// --- internal logic is same for both types ---
}
// create:
Transaction t = new Transaction(Transaction.IN);
这种情况的最佳做法是什么?我应该声明一个枚举?两个班?我应该使用工厂模式吗?
【问题讨论】:
-
最佳实践是两个类:可能是
InTransaction和OutTransaction或IncomeTransaction和ExpenseTransaction。如果有用的话,两者都可以扩展Transaction。 -
交易中还有什么?类型只是以后分类的标记,还是会驱动 Transaction 方法的行为差异?如果它只是一条数据,你得到的很好,但如果不同的 Transactions 会有不同的行为,你最好创建不同的类。
-
它只是一个标记,它被视图模块使用。两者的事务内部逻辑相同。
-
为此目的声明一个枚举。
-
System.out 不同,这是有两个类的一个很好的理由,你不需要开关(这是一种强烈的设计味道)。