Java 按不同顺序调用接口方法
我有一个带有多种方法的接口:Java 按不同顺序调用接口方法,java,design-patterns,Java,Design Patterns,我有一个带有多种方法的接口: interface IExample { methodA(); methodB(); methodC(); ... methodN(); } 我也有该接口的几个实现(例如A类、B类…)。我还有一个HashMap,我在其中根据特定键放置了这些实现: commands = new HashMap<String, IExample>(); commands.put("key1", new A()); . . commands.put("keyN",
interface IExample {
methodA();
methodB();
methodC();
...
methodN();
}
我也有该接口的几个实现(例如A类、B类…)。我还有一个HashMap,我在其中根据特定键放置了这些实现:
commands = new HashMap<String, IExample>();
commands.put("key1", new A());
.
.
commands.put("keyN", new N());
现在我能够调用特定实现的方法:
example.methodA();
...
问题在于,根据事件的不同,方法调用顺序不同。因此,对于键1,调用顺序为:
example.methodC();
example.methodA();
...
example.methodA()
example.methodC()
...
但是对于不同的键,比如说键2,方法调用顺序是:
example.methodC();
example.methodA();
...
example.methodA()
example.methodC()
...
我可以使用什么样的设计模式或方法来轻松、干净地解决这个问题?不要使用这样的东西:
if (example instance of A) { call order for A... }
if (example instance of B) { call order for B... }
我会这样做: 创建一个接口
IExecuteOrder
,方法是:executeOrder(IExample示例)代码>
然后根据执行顺序在不同的类中实现executeOrder
方法。
前
然后将这些实现放在一个类似于的映射中
Map<String, IExecuteOrder> map = new HashMap<>();
map.put("key1", new ExecuteOrder1());
map.put("key2", new ExecuteOrder2());
...
map.put("keyn", new ExecuteOrderN());
只需将另一个方法添加到IExample
界面:
interface IExample {
methodA();
methodB();
methodC();
...
methodN();
execute();
}
class A implements IExample {
//...
execute() {
methodA();
methodC();
}
}
...
commands.get("key1").execute();
interface IExample {
methodA();
methodB();
methodC();
// ...
methodN();
runInOrder();
}
在这种情况下,如果无法更改IExample
接口,或者有许多订单重复,则可以将execute()
方法移动到另一个接口IExecutor
:
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
:
commands = new HashMap<String, IExecutor>();
commands.put("key1", new Executor1(new ExampleA()));
commands.put("key2", new Executor1(new ExampleB()));
...
commands.get("key1").execute();
commands=newhashmap();
commands.put(“key1”,newexecutor1(newexamplea());
commands.put(“key2”,newexecutor1(newexampleb());
...
commands.get(“key1”).execute();
我只需在IExample
界面中声明另一个方法:
interface IExample {
methodA();
methodB();
methodC();
...
methodN();
execute();
}
class A implements IExample {
//...
execute() {
methodA();
methodC();
}
}
...
commands.get("key1").execute();
interface IExample {
methodA();
methodB();
methodC();
// ...
methodN();
runInOrder();
}
每个类都需要实现这个runinoorder
方法,它只需按照执行所需的顺序调用methodX
方法
也就是说,类A
(匹配“key1”
)将实现runInOrder
,如下所示:
@Override
public void runInOrder() {
this.methodC();
this.methodA();
}
等等。然后,您可以执行以下操作:
Event event = ...
IExample example = UtilClass.commands.get(event.getKey());
example.runInOrder();
您可以编写一个方法,以某种顺序调用其他方法,并在需要时以不同的顺序重写它。这是if(instanceof)
code的正常替代方案。