diff --git a/notes/设计模式.md b/notes/设计模式.md index 3dc9c2aa..61bd7f29 100644 --- a/notes/设计模式.md +++ b/notes/设计模式.md @@ -473,7 +473,118 @@ public class Client { ### 意图 -将命令封装进对象中;允许使用命令对象对客户对象进行参数化;允许将命令对象存放到队列中。 +将命令封装成对象中,以便使用命令来参数化其它对象,或者将命令对象放入队列中进行排队,或者将命令对象的操作记录到日志中,以及支持可撤销的操作。 + +### 类图 + +- Command:命令 +- Receiver:命令接收者,也就是命令真正的执行者 +- Invoker:通过它来调用命令 +- Client:可以设置命令与命令的接收者 + +

+ +### 实现 + +设计一个要控制,可以控制电灯开关。 + +

+ +```java +public interface Command { + void execute(); +} +``` + +```java +public class LightOnCommand implements Command { + Light light; + + public LightOnCommand(Light light) { + this.light = light; + } + + @Override + public void execute() { + light.on(); + } +} +``` + +```java +public class LightOffCommand implements Command { + Light light; + + public LightOffCommand(Light light) { + this.light = light; + } + + @Override + public void execute() { + light.off(); + } +} +``` + +```java +public class Light { + + public void on() { + System.out.println("Light is on!"); + } + + public void off() { + System.out.println("Light is off!"); + } +} +``` + +```java +/** + * 遥控器 + */ +public class Invoker { + private Command[] onCommands; + private Command[] offCommands; + private final int slotNum = 7; + + public Invoker() { + this.onCommands = new Command[slotNum]; + this.offCommands = new Command[slotNum]; + } + + public void setOnCommand(Command command, int slot) { + onCommands[slot] = command; + } + + public void setOffCommand(Command command, int slot) { + offCommands[slot] = command; + } + + public void onButtonWasPushed(int slot) { + onCommands[slot].execute(); + } + + public void offButtonWasPushed(int slot) { + offCommands[slot].execute(); + } +} +``` + +```java +public class Client { + public static void main(String[] args) { + Invoker invoker = new Invoker(); + Light light = new Light(); + Command lightOnCommand = new LightOnCommand(light); + Command lightOffCommand = new LightOffCommand(light); + invoker.setOnCommand(lightOnCommand, 0); + invoker.setOffCommand(lightOffCommand, 0); + invoker.onButtonWasPushed(0); + invoker.offButtonWasPushed(0); + } +} +``` ### JDK @@ -1336,6 +1447,8 @@ public class Client { ### 实现 +观看电影需要操作很多电器,使用外观模式可以实现一键看电影功能。 + ```java public class SubSystem { public void turnOnTV() { diff --git a/pics/ae1b27b8-bc13-42e7-ac12-a2242e125499.png b/pics/ae1b27b8-bc13-42e7-ac12-a2242e125499.png new file mode 100644 index 00000000..27977740 Binary files /dev/null and b/pics/ae1b27b8-bc13-42e7-ac12-a2242e125499.png differ diff --git a/pics/e6bded8e-41a0-489a-88a6-638e88ab7666.jpg b/pics/e6bded8e-41a0-489a-88a6-638e88ab7666.jpg new file mode 100644 index 00000000..f4aa12a0 Binary files /dev/null and b/pics/e6bded8e-41a0-489a-88a6-638e88ab7666.jpg differ