您的位置:首页 > 其它

设计模式-命令模式

2016-01-07 11:53 141 查看
命令模式(Command)

    命令模式很好理解,举个例子,司令员下令让士兵去干件事情,从整个事情的角度来考虑,司令员的作用是,发出口令,口令经过传递,传到了士兵耳朵里,士兵去执行。这个过程好在,三者相互解耦,任何一方都不用去依赖其他人,只需要做好自己的事儿就行,司令员要的是结果,不会去关注到底士兵是怎么实现的。

    命令模式一般为三部分:接受者(Receiver)、命令(Command)、调用者(Invoker)

接受者代码

public class Receiver {
public void action(){
System.out.println("Roger that!");
}
}


命令代码

public class Command {

private Receiver receiver;

public Command(Receiver receiver){
this.receiver=receiver;
}

public void execute(){
receiver.action();
}
}


调用者代码

public class Invoker {

private Command command;

public Invoker(Command command){
this.command=command;
}
public void action(){
command.execute();
}
}


测试

public class Demo {
public static void main(String[] args) {
Receiver receiver=new Receiver();
Command command=new Command(receiver);
Invoker invoker=new Invoker(command);
invoker.action();
}

}


测试结果:

Roger that!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: