调用者和执行者分割开,
和中介者模式很像。其实也是加了个中间层。
不过中介者模式,是将两人之间的必须要发生联系的操作,明确出来。
而这个是,为了可以好解绑,和加绑,比如执行者发生变化,对于调用者,是透明的。
调用者发生变化,执行者也不知道,只需要改一半的代码。
class Invoker{
private Command command;
public void setCommand(Command command){
this.command = command;
}
public void action(){
this.command.execute();
}
}
abstract class Command{
public abstract void execute();
}
class ConcreteCommand extends Command{
private Receiver receiver;
public ConcreteCommand(Receiver receiver){
this.receiver=receiver;
}
@Override
public void execute() {
this.receiver.doSomething();
}
}
class Receiver{
public void doSomething(){
System.out.println("receiver do something");
}
}
public class CommandTest {
public static void main(String[] args){
Receiver receiver = new Receiver();
Command command = new ConcreteCommand(receiver);
command.execute();
Invoker invoker=new Invoker();
invoker.setCommand(command);
invoker.action();
}
}
网友评论