1.命令模式概念
命令模式(Command Pattern),將“請求”封裝成對象,以便使用不同的請求攻冷,隊列或日志來參數(shù)化其他對象丈攒。命令模式也支持可撤銷操作。它屬于行為型模式狞甚。
2.命令模式作用
命令模式將發(fā)出請求的對象和執(zhí)行請求的對象解耦锁摔。被解耦的兩個對象是通過命令對象來進行溝通的。命令對象封裝了接收者和一個或一組動作哼审。調(diào)用者可以接收命令作為參數(shù)谐腰,甚至在運行時動態(tài)的進行。
3.何時使用
認為是命令的地方都可以使用命令模式涩盾,比如: 1十气、GUI 中每一個按鈕都是一條命令。 2春霍、模擬 CMD砸西。
4.優(yōu)點和缺點
優(yōu)點
1、降低了系統(tǒng)耦合度址儒。
2籍胯、新的命令可以很容易添加到系統(tǒng)中去。
缺點
使用命令模式可能會導致某些系統(tǒng)有過多的具體命令類离福。
5.例子解析
命令模式類圖
這個例子是關(guān)于通過遙控器發(fā)出開燈和關(guān)燈的命令杖狼。命令由遙控器發(fā)出,執(zhí)行者是電燈妖爷。
Command接口:
public interface Command {
public void excute();
//undo的作用是撤銷操作
public void undo();
}
命令的具體對象一:關(guān)燈命令
public class LightOffCommand implements Command{
Light light = null;
public LightOffCommand(Light light) {
this.light = light;
}
@Override
public void excute() {
light.off();
}
@Override
public void undo() {
light.on();
}
}
命令的具體對象:開燈命令
public class LightOnCommand implements Command {
Light light = null;
public LightOnCommand(Light light) {
this.light = light;
}
@Override
public void excute() {
light.on();
}
@Override
public void undo() {
light.off();
}
}
接收者Receiver(接收命令蝶涩,執(zhí)行命令的對象):電燈
public class Light {
String name;
public Light(String name) {
this.name = name;
}
public void on() {
System.out.println(name+" 開燈");
}
public void off() {
System.out.println(name+" 關(guān)燈");
}
}
Invoker對象:
public class SimpleRemoteControl {
Command slot;
public SimpleRemoteControl() {
// TODO Auto-generated constructor stub
}
public void setCommand(Command command) {
slot = command;
}
public void buttonWasPress() {
slot.excute();
}
}
客戶端對象:
/**
* @author Administrator
* 用電燈做例子:
* Invoker---SimpleRemoteControl
* Command---Command
* ConreteCommand---LightOnCommand理朋,LightOffCommand
* Receiver---Light
*/
public class RemoteControlTest {
public static void main(String[] args) {
SimpleRemoteControl simpleRemoteControl = new SimpleRemoteControl();
simpleRemoteControl.setCommand(new LightOnCommand(new Light("Living Room")));
simpleRemoteControl.buttonWasPress();
}
}
6.源碼地址
http://download.csdn.net/detail/lgywsdy/9749545