java - 以不同顺序调用接口(interface)方法

标签 java design-patterns

我有一个接口(interface)和多个方法:

interface IExample {
 methodA();
 methodB();
 methodC();
 ...
 methodN();
}

我还有该接口(interface)的多个实现(例如 A 类、B 类...)。我还有 HashMap,我将这些实现放在基于特定键的地方:

commands = new HashMap<String, IExample>();
commands.put("key1", new A());
.
.
commands.put("keyN", new N());

我使用策略设计模式在某些事件发生时获取每个实现:

Event event = ...
IExample example = UtilClass.commands.get(event.getKey());

现在我可以调用特定实现的方法了:

example.methodA();
...

问题是根据事件,方法调用顺序是不同的。因此,对于 key1 调用顺序是:

example.methodC();
example.methodA();
...

但是对于不同的key,比如说key2,方法调用顺序是:

example.methodA()
example.methodC()
...

我可以使用什么设计模式或方法来以简单干净的方式解决这个问题?不要使用这样的东西:

 if (example instance of A) {    call order for A... }

 if (example instance of B) {    call order for B... }

最佳答案

您只需将另一个方法添加到您的IExample 接口(interface):

interface IExample {
    methodA();
    methodB();
    methodC();
    ...
    methodN();

    execute();
}

class A implements IExample {
    //...
    execute() {
        methodA();
        methodC();
    }
}

...

commands.get("key1").execute();

如果 IExample 接口(interface)无法更改,或者有很多重复的命令,您可以将 execute() 方法移动到另一个接口(interface) I执行器:

interface IExecutor {
    execute();
}

class Executor1 implements IExecutor {
    private final IExample example;
    public Executor1(IExample example) { this.example = example; }
    execute() {
        example.methodA();
        example.methodC();
    }
}

并管理 IExecutor 而不是 IExample 的 HashMap :

commands = new HashMap<String, IExecutor>();
commands.put("key1", new Executor1(new ExampleA()));
commands.put("key2", new Executor1(new ExampleB()));
...
commands.get("key1").execute();

关于java - 以不同顺序调用接口(interface)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40024830/

相关文章:

java - 什么时候应该使用工厂方法模式? (而不是组合)

java - 如何从 Java 函数返回值?

java - 同一文件中的多个 JPanel 定义

PHPUnit,在我对抽象类及其子类的测试中避免重复的正确方法

java - "Adopting MapReduce model"= 可扩展性的通用答案吗?

c++ - 如何使调用代码对被调用的代码一无所知

java - 泛化类的 ArrayList 之间的搜索方法

java - 王牌 :chart how to set xAxis tick with AxisType:DATE

java - Spring security UserDetailsS​​ervice 不工作

python - 用于处理机器学习大型数据集的设计模式