命令模式
命令(Command)模式:将一个请求封装为一个对象,使发出请求的责任和执行请求的责任分割开。这样两者之间通过命令对象进行沟通,这样方便将命令对象进行储存、传递、调用、增加与管理。
案例
一个命令执行者可以执行多个命令
public class Receiver {public void eat(){System.out.println("正在吃饭。。。");}public void sleep(){System.out.println("开始睡觉。。");}
}
public interface Commond {void execute();
}
public class EatCommond implements Commond{private Receiver receiver = new Receiver();@Overridepublic void execute() {receiver.eat();}
}
public class SleepCommond implements Commond{private Receiver receiver = new Receiver();@Overridepublic void execute() {receiver.sleep();}
}
命令发出者只需要设置命令就能执行
public class Invoker {Commond commond;public void call(){commond.execute();}public void setCommond(Commond commond){this.commond = commond;}
}