命令模式,显而易见,是将命令和实际操作相隔离,解耦合,客户端只发出命令,具体的操作不需要关心,只需要完成任务。举个很简单的例子,用户点菜,然后厨师做菜,根据点菜的口味不同厨师做不同的菜,
一般来说,主要有三个对象
一个是抽象接口类,用于封装命令执行方法。
一个命令执行类(invoker):这个类主要将具体的命令传给具体的执行者。
抽象命令执行类(receiver)
还有一个类就是命令具体执行的类(Concretereceiver),封装了具体的命令
代码演示下:
抽象的命令接口类
package command;
public interface AbstractAction {
public void excute();
}
具体命令类
package command;
public class Action1 implements AbstractAction{
//构造接受者
private AbstractReceiver receiver;
public Action1(AbstractReceiver receiver){
this.receiver=receiver;
}
//根据具体的命令给具体的接收者
@Override
public void excute() {
System.out.println("命令1发布.....");
this.receiver.cook();
}
}
package command;
public class Action2 implements AbstractAction{
//构造接受者
private AbstractReceiver receiver;
public Action2(AbstractReceiver receiver){
this.receiver=receiver;
}
//根据具体的命令给具体的接收者
@Override
public void excute() {
System.out.println("命令2发布.....");
this.receiver.cook();
}
}
调用者类
package command;
public class Invoker {
private ActionInterface command;
public void setCommand(ActionInterface command) {
this.command = command;
}
public void action(){
this.command.excute();
}
}
抽象命令执行者类
package command;
public abstract class AbstractReceiver {
public abstract void cook();
}
具体命令执行类
package command;
public class Receiver1 extends AbstractReceiver{
@Override
public void cook() {
System.out.println("执行命令1完成.....");
}
}
package command;
public class Receiver2 extends AbstractReceiver{
@Override
public void cook() {
System.out.println("执行命令2完成.....");
}
}
测试类
package command;
public class Test {
public static void main(String[] args) {
//创建调用者
Invoker invoker=new Invoker();
//创建命令接收者
AbstractReceiver receiver=new Receiver1();
//创建命令,传入接收者
AbstractAction command=new Action1(receiver);
//发布命令
invoker.setCommand(command);
//执行
invoker.action();
}
}
结果
命令1发布..... 执行命令1完成.....