易学设计模式四 命令模式(Commond)
命令模式定义
将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤销的操作。
命令模式有4个角色,一个
Command:声明执行操作的接口。
ConcreteCommand:将一个接收者对象邦定于一个动作。调用者收者相应的操作,以实现Execute。
Invoker(Dealer):要求该命令执行这个请求。
Receiver(Light):知道如何实施与执行一个请求相关的操作,任何类都可能是一个接收者。
命令接口
public interface Commond {public void execute();public void undo();}
public class LightOnCommond implements Commond {private Light light;public LightOnCommond(Light light) {this.light = light;}public void execute() {light.on();}public void undo() {light.off();}}
public class LightOffCommond implements Commond {private Light light;public LightOffCommond(Light light) {this.light = light;}public void execute() {light.off();}public void undo() {light.on();}}
public class Light {private String state;public Light() {state = "Off";}public void on() {System.out.println("Turn the light on");state = "On";}public void off() {System.out.println("Turn the light off");state="off";}public String getState() {return state;}}
public class Dealer {private Vector v;public Dealer() {v = new Vector();}public void deal(Commond cmd) {v.addElement(cmd);cmd.execute();}public void unDeal() {if(v.size() > 0) {Commond cmd = (Commond)v.get(v.size()-1);cmd.undo();v.remove(v.size()-1);} }}
public class Client {public static void main(String[] args) {Light light = new Light();Dealer dealer = new Dealer();Commond onCmd = new LightOnCommond(light);dealer.deal(onCmd);Commond offCmd = new LightOffCommond(light);dealer.deal(offCmd);dealer.unDeal();}}