Invoker是调用者(司令员),Receiver是被调用者(士兵),MyCommand是命令,实现了Command接口,持有接收对象!
/**
* @author: muyichun
* @date : 2016年3月23日18:11:35
* @function: 命令模式
*/
public class Main{
public static void main(String[] args) {
Receiver receiver = new Receiver();
Command command = new MyCommand(receiver);
Invoker invoker = new Invoker(command);
invoker.action();
}
}
//命令接口
interface Command{
public void exe();
}
//命令实现类
class MyCommand implements Command{
private Receiver receiver;
public MyCommand(Receiver receiver){
this.receiver = receiver;
}
@Override
public void exe() {
receiver.action();
}
}
//执行者
class Receiver {
public void action() {
System.out.println("command received!");
}
}
//命令官
class Invoker{
private Command command;
public Invoker(Command command){
this.command = command;
}
public void action(){
command.exe();
}
}
——贴上自己喜欢的代码!