2(+1)要求
1.-用户必须能够添加多种类型的设备
2.-如果设备类型为“某些值”,则...
N.- ...将来的要求...现在,当设备类型为“某些其他值”时...
这种情况是,一方面,我知道“类型”可以更改,但是我也知道某些值必须存在“类型”的特定值才能执行特定的行为。
private int SomeAction(Equipment e)
{
if (e.Type == "SOME VALUE")
{
// Do something for that special case
}
else if (e.Type == "SOME OTHER VALUE")
{
// Do something for that other special case
}
else
{
// Do the other thing
}
}
答案 0 :(得分:0)
一个选择是将逻辑放入Equipment
类中,如@NicoGranelli在上述注释中所建议。这是一个好方法,特别是如果您有Equipment
另一种替代方法是排除Action
接口。您将有不同的Action
实现,并将每种设备类型映射到特定操作。通过这种方法,您消除了条件条件。它还简化了每个Action
实现的单元测试。
interface EquipmentAction { void perform(); }
class SomeAction implements EquipmentAction { void perform() { ... } }
class SomeOtherAction implements EquipmentAction { void perform() { ... } }
class DefaultAction implements EquipmentAction { void perform() { ... } }
class Client {
private final Map<EquipmentType,EquipmentAction> equipmentActions = buildEquipmentActionMap();
private final EquipmentAction DEFAULT_ACTION = new DefaultAction();
private int SomeAction(Equipment equipment) {
EquipmentAction action = equipmentActions.getOrDefault(equipment.Type, DEFAULT_ACTION);
action.perform();
}
}