码迷,mamicode.com
首页 > 其他好文 > 详细

6.命令模式

时间:2017-09-02 18:00:57      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:out   this   logs   system   static   rate   images   做了   off   

1.定义命令接口

public interface Command {
	public void execute();
}

2.具体需要调用到的方法的类

public class Light {
	public void on(){
		System.out.println("Light on");
	}
	public void off(){
		System.out.println("Light off");
		
	}
}
public class GarageDoor {
	public void up(){
		System.out.println("Garage Door is Open");
	}
	public void down(){
		System.out.println("Garage Door Down");
	}
	public void stop(){
		System.out.println("GarageDoor stop");
	}
	public void lightOn(){
		System.out.println("GarageDoor LightOn ");
	}
	public void lightOff(){
		System.out.println("GarageDoor lIghOff");
	}
	
}

3.这些具体要调用到的方法的类的对应具体命令类

public class LightOnCommand implements Command {
	private Light light;
	public LightOnCommand(Light light){
		this.light=light;
	}
	public void execute() {
		// TODO Auto-generated method stub
		this.light.on();
	}

}
public class GarageDoorOpenCommand implements Command{
	private GarageDoor door;
	public GarageDoorOpenCommand(GarageDoor door){
		this.door=door;
	}
	public void execute() {
		// TODO Auto-generated method stub
		this.door.up();
	}
	
}

4.客户程序

public class SimpleRemoteControl {
	private Command command;
	public void setCommand(Command command){
		this.command=command;
	}
	public void buttonWasPressed(){
		this.command.execute();
	}
}

5.应用

public class App {
	public static void main(String[] args) {
		SimpleRemoteControl control=new SimpleRemoteControl();
		//1
		Light light=new Light();
		Command lightOn=new LightOnCommand(light);
		
		control.setCommand(lightOn);
		control.buttonWasPressed();
		//2
		GarageDoor door=new GarageDoor();
		Command doorOpen=new GarageDoorOpenCommand(door);
		control.setCommand(doorOpen);
		control.buttonWasPressed();
	}
	
	
}

6.结果应该是这样的

技术分享

 tip: 而命令模式中,经典的批处理,撤销,重做。其实就是在客户程序中,比如用list集合缓存一批命令对象,批调用就实现了批处理,然后在每次调用时也缓存这次调用的命令方法,下次重新执行最后一次执行的相反的缓存命令或此缓存命令就实现撤销或重做了。

6.命令模式

标签:out   this   logs   system   static   rate   images   做了   off   

原文地址:http://www.cnblogs.com/Niel-3/p/7467129.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!