设计模式:命令模式
什么是命令模式
命令模式把请求封装成对象,对请求发送者和接收者进行解耦。是一种行为型模式。
命令模式的结构
- Invoker(请求发送者)
- Command(抽象请求)
- ConcreteCommand(抽象请求的具体实现)
- Receiver(请求接收者)
- Client(客户端)
命令模式的一个实例
有一个开关(switch)、灯(lamp)和两种行为开灯(on)以及关灯(off)。在这里开关为请求发送者,灯为接收者,开灯和关灯为两个请求对象。
实例代码
Command
public abstract class Command {
abstract void execute();
}
Lamp
public class Lamp {
public void on(){
System.out.println("Lamp on ...");
}
public void off(){
System.out.println("Lamp off ...");
}
}
Switch
public class Switch {
private List<Command> history = new ArrayList<Command>();
private Command command;
public Switch(Command command){
this.command = command;
}
public void setCommand(Command command){
this.command = command;
}
public void call(){
history.add(command);
command.execute();
}
public void showHis(){
for (Command command:history){
System.out.println(command);
}
}
}
OnCommand
public class OnCommand extends Command {
private Lamp lamp;
public OnCommand(Lamp lamp) {
this.lamp = lamp;
}
@Override
void execute() {
lamp.on();
}
public String toString(){
return "Execute on.";
}
}
OffCommand
public class OffCommand extends Command {
private Lamp lamp;
public OffCommand(Lamp lamp) {
this.lamp = lamp;
}
@Override
void execute() {
lamp.off();
}
public String toString(){
return "Execute off.";
}
}
Client
public class Client {
public static void main(String args[]) {
Lamp lamp = new Lamp();
Command command1 = new OnCommand(lamp);
Switch s = new Switch(command1);
s.call();
Command command2 = new OffCommand(lamp);
s.setCommand(command2);
s.call();
s.showHis();
}
}
实例结果
Lamp on ...
Lamp off ...
Execute on.
Execute off.
(完)