设计模式——命令模式

命令模式:

将请求封装成对象,从而使用不同的请求、队列以及日志来参数化其他对象。命令对象支持可撤销的操作。命令对象将动作和接收者包进对象中。实现“行为请求者”与“行为实现者”解耦。

要点: 命令对象中动作和接收者被绑在一起,控制器调用命令对象的execute方法。

应用: 线程池、队列请求、日志请求。

类图:

设计模式——命令模式_第1张图片

 

以下程序模拟一个控制器对客厅的灯和车库的门进行控制。

1.定义灯

package net.dp.command.simpleremote;

public class Light {

	public Light() {
	}

	public void on() {
		System.out.println("Light is on");
	}

	public void off() {
		System.out.println("Light is off");
	}
}

  

2.定义车库的门

package net.dp.command.simpleremote;

public class GarageDoor {

	public GarageDoor() {
	}

	public void up() {
		System.out.println("Garage Door is Open");
	}

	public void down() {
		System.out.println("Garage Door is Closed");
	}

	public void stop() {
		System.out.println("Garage Door is Stopped");
	}

	public void lightOn() {
		System.out.println("Garage light is on");
	}

	public void lightOff() {
		System.out.println("Garage light is off");
	}
}

  

3.定义命令接口

package net.dp.command.simpleremote;

public interface Command {
	public void execute();
}

  

4.实现命令接口

package net.dp.command.simpleremote;

public class LightOnCommand implements Command {
	Light light;
  
	public LightOnCommand(Light light) {
		this.light = light;
	}
 
	public void execute() {
		light.on();
	}
}

  

package net.dp.command.simpleremote;

public class LightOffCommand implements Command {
	Light light;
 
	public LightOffCommand(Light light) {
		this.light = light;
	}
 
	public void execute() {
		light.off();
	}
}

  

package net.dp.command.simpleremote;

public class GarageDoorOpenCommand implements Command {
	GarageDoor garageDoor;

	public GarageDoorOpenCommand(GarageDoor garageDoor) {
		this.garageDoor = garageDoor;
	}

	public void execute() {
		garageDoor.up();
	}
}

  

5.编写控制器,实现命令的调用

package net.dp.command.simpleremote;

//
// This is the invoker
//
public class SimpleRemoteControl {
	Command slot;
 
	public SimpleRemoteControl() {}
 
	public void setCommand(Command command) {
		slot = command;
	}
 
	public void buttonWasPressed() {
		slot.execute();
	}
}

  

6.写完啦!!

package net.dp.command.simpleremote;

public class RemoteControlTest {
	public static void main(String[] args) {
		SimpleRemoteControl remote = new SimpleRemoteControl();
		Light light = new Light();
		GarageDoor garageDoor = new GarageDoor();
		LightOnCommand lightOn = new LightOnCommand(light);
		GarageDoorOpenCommand garageOpen = new GarageDoorOpenCommand(garageDoor);

		remote.setCommand(lightOn);
		remote.buttonWasPressed();
		remote.setCommand(garageOpen);
		remote.buttonWasPressed();
	}
}

 

 

你可能感兴趣的:(设计模式——命令模式)