【问题标题】:Is there a Design Pattern that solve this problem?有没有解决这个问题的设计模式?
【发布时间】:2019-11-29 21:23:36
【问题描述】:

2 (+1) 个要求

1.- 用户必须能够添加多种类型的设备
2.- 当设备类型为“SOME VALUE”时...
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
    }
}

【问题讨论】:

  • 这取决于业务逻辑。如果您可以将“特殊情况逻辑”放置在设备本身中,那么您将不需要那些链接的 if。如果您解释更多有关该域的信息,将很容易为您提供帮助
  • thank you from Chile NicoGranelli 该域名是关于机械设备的零件,这些零件有用户可以创建的“类型”,例如:零件类型:“轮子”、“门”、“锁” ”。然后需要对某些类型的部件进行特定的行为:“在门的情况下,执行这个或那个动作”
  • 嗨,马诺洛!假设您不能将该逻辑移动到设备类中,我有两个想法:1)如果逻辑是从外部触发的,那么访问者模式可能会很有用。访问者将了解每种设备类型和相关的逻辑。这不是一个很好的解决方案,但有时您必须接受这一点 2)如果当时触发了一个设备的逻辑,我将尝试使用事件和事件调度程序。逻辑将驻留在事件处理程序中

标签: oop design-patterns


【解决方案1】:

一种选择是按照@NicoGranelli 在上述评论中的建议将逻辑放入Equipment 类中。这是一个很好的方法,特别是如果您有不同的 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();
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-11
    • 2021-04-16
    • 2021-04-02
    • 2014-04-03
    相关资源
    最近更新 更多