【问题标题】:Command pattern with too many classes具有太多类的命令模式
【发布时间】:2013-06-14 11:29:55
【问题描述】:

我们的遗留代码有很长的 if else 块代码,这些代码取决于事件和对象类型

if(event == A && objectType == O1){
.....
}
else if (event == A && objectType == O2){
 ....
}
else if (....)
....
....

随着越来越多的条件引入,我正在考虑将这个逻辑替换为每个条件的命令模式。但是所需的类数是(事件数)*(对象类型数)。有没有更简单的方法来重构这段代码?

【问题讨论】:

  • 不能直接想到任何东西,但是你总是可以在你的IDE或编辑器中编写一些宏......无论如何都值得这样做,你使用命令模式的代码会更清晰。
  • 如果条件块的内容完全不同,则不。如果他们根据event 和/或objectType 共享某种通用逻辑,那么是的。

标签: java design-patterns


【解决方案1】:

创建一个包含eventobjectType的类,使其实现.equals().hashCode()。也为每个执行块创建一个通用类。

然后您就可以使用Map 并且简单的查找将返回需要执行的内容。

【讨论】:

    【解决方案2】:

    您可能正在寻找的模式通常称为双重调度或有时称为访客模式。 http://en.wikipedia.org/wiki/Visitor_pattern

    为事件创建一组类,为对象类型创建一组。创建接口

    public interface VisitEvent {
        public void visit(EventA eventA);
        public void visit(EventB eventB);
        // for each event class
    }
    

    在事件类中,你必须在对象类型类上调用访问模式。

    public class EventA {
        public void visit(ObjectTypeParent otp) {
            otp.visit(this);
        }
    }
    

    假设对象类型类继承自一个通用类

    public abstract class ObjectTypeParent implements VisitEvent {
        public void visit(EventA eventA) {
            // default code here
        }
        // same for each event visit from VisitEvent
    }
    

    然后

    public class ObjectType01 extends ObjectTypeParent {
        public void visit(EventA eventA) {
           // stuff you want done for this combination
        }
        // don't implement the ones that have common behavior
    }
    

    【讨论】:

      猜你喜欢
      • 2019-09-21
      • 1970-01-01
      • 1970-01-01
      • 2022-11-23
      • 1970-01-01
      • 1970-01-01
      • 2021-09-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多