1.命令模式概念
命令模式(Command Pattern),將“請(qǐng)求”封裝成對(duì)象,以便使用不同的請(qǐng)求,隊(duì)列或日志來(lái)參數(shù)化其他對(duì)象。命令模式也支持可撤銷操作。它屬于行為型模式。
2.命令模式作用
命令模式將發(fā)出請(qǐng)求的對(duì)象和執(zhí)行請(qǐng)求的對(duì)象解耦。被解耦的兩個(gè)對(duì)象是通過(guò)命令對(duì)象來(lái)進(jìn)行溝通的。命令對(duì)象封裝了接收者和一個(gè)或一組動(dòng)作。調(diào)用者可以接收命令作為參數(shù),甚至在運(yùn)行時(shí)動(dòng)態(tài)的進(jìn)行。
3.何時(shí)使用
認(rèn)為是命令的地方都可以使用命令模式,比如: 1、GUI 中每一個(gè)按鈕都是一條命令。 2、模擬 CMD。
4.優(yōu)點(diǎn)和缺點(diǎn)
優(yōu)點(diǎn)
1、降低了系統(tǒng)耦合度。
2、新的命令可以很容易添加到系統(tǒng)中去。
缺點(diǎn)
使用命令模式可能會(huì)導(dǎo)致某些系統(tǒng)有過(guò)多的具體命令類。
5.例子解析
命令模式類圖
這個(gè)例子是關(guān)于通過(guò)遙控器發(fā)出開燈和關(guān)燈的命令。命令由遙控器發(fā)出,執(zhí)行者是電燈。
Command接口:
public interface Command {
public void excute();
//undo的作用是撤銷操作
public void undo();
}
命令的具體對(duì)象一:關(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();
}
}
命令的具體對(duì)象:開燈命令
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í)行命令的對(duì)象):電燈
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對(duì)象:
public class SimpleRemoteControl {
Command slot;
public SimpleRemoteControl() {
// TODO Auto-generated constructor stub
}
public void setCommand(Command command) {
slot = command;
}
public void buttonWasPress() {
slot.excute();
}
}
客戶端對(duì)象:
/**
* @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