調(diào)用者和執(zhí)行者分割開,
和中介者模式很像十籍。其實(shí)也是加了個(gè)中間層蛆封。
不過中介者模式,是將兩人之間的必須要發(fā)生聯(lián)系的操作勾栗,明確出來惨篱。
而這個(gè)是,為了可以好解綁械姻,和加綁,比如執(zhí)行者發(fā)生變化机断,對(duì)于調(diào)用者楷拳,是透明的。
調(diào)用者發(fā)生變化吏奸,執(zhí)行者也不知道欢揖,只需要改一半的代碼。
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();
}
}