转自于《设计模式之禅》
通用Receiver类
public abstract class Receiver{
public abstract void doSomething();
}
具体的Receiver类
public class ConcreteReciver1 extends Receiver{
public void do doSomething(){
}
}
public class ConcreteReciver2 extends Receiver{
public void do doSomething(){
}
}
抽象的Command类
public abstract class Command{
public abstract void execute();
}
具体的Command类
public class ConcreteCommand1 extends Command(){
public Receiver receiver;
public ConcreteCommand1(Receiver _receiver){
this.receiver = _receiver;
}
public void execute(){
this.receiver.doSomething();
}
}
public class ConcreteCommand2 extends Command(){
public Receiver receiver;
public ConcreteCommand1(Receiver _receiver){
this.receiver = _receiver;
}
public void execute(){
this.receiver.doSomething();
}
}
调用者Invoker类
public class Invoker{
private Command command;
public void setCommand(Command _command){
this.command = _command;
}
public void action(){
this.command.execute();
}
}
场景调用:
public class Main{
public static void main(String[] args){
Invoker invoker = new Invoker();
Receiver receiver = new ComcreteReceiver1();
Command command = new ConcreteCommand1(receiver);
invoker.setCommand(command);
invoker.action();
}
}
命令模式可以结合责任链模式,实现命令族解析任务;结合模板方法模式,则可以减少Command子类的膨胀问题。
命令模式的使用场景:
只要你认为是命令的地方就可以采用命令模式,例如,在GUI开发中,一个按钮的点击是一个命令,可以采用命令模式;模拟DOS命令的时候,当然也要采用命令模式;触发-反馈机制的处理等。