1. 命令模式
- 将动作的请求者和动作的执行者分开,达到解耦的目的
- 命令的发布者,并不清楚具体事谁来执行
- 具体的请求封装成一个对象, 支持撤销
- 角色: 命令发布者(Invoker)
命令具体执行者(Reveiver)
命令(Command) 链接二发布者和执行者
- 命令模式的操作相对比较简单,一般只有执行和撤回两个命令
- 空对象模式:当调用空对象的方法的时候,什么也不做,可以省略掉对空判断
package com.nike.erick.commond;
import lombok.AllArgsConstructor;
public class Test {
public static void main(String[] args) {
RemoteController remoteController = new RemoteController(10);
remoteController.onButton(0, new LightCommand(new LightReceiver()));
remoteController.offButton(0, new LightCommand(new LightReceiver()));
}
}
interface Command {
void execute(String state);
void rollback(String state);
}
@AllArgsConstructor
class LightCommand implements Command {
public Receiver receiver;
@Override
public void execute(String state) {
if (state == "on") {
receiver.on();
} else if (state == "off") {
receiver.off();
}
}
@Override
public void rollback(String state) {
if (state == "off") {
receiver.on();
} else if (state == "on") {
receiver.off();
}
}
}
class BlankCommand implements Command {
@Override
public void execute(String state) {
}
@Override
public void rollback(String state) {
}
}
interface Receiver {
void on();
void off();
}
class LightReceiver implements Receiver {
@Override
public void on() {
System.out.println("打开电灯");
}
@Override
public void off() {
System.out.println("关闭电灯");
}
}
class RemoteController {
public int commandPairs;
public Command[] offCommands;
public Command[] onCommands;
public Command rollbackCommand;
public RemoteController(int commandPairs) {
this.commandPairs = commandPairs;
if (commandPairs <= 0) {
throw new IllegalArgumentException("Command Paris Illegal");
}
offCommands = new Command[commandPairs];
onCommands = new Command[commandPairs];
BlankCommand blankCommand = new BlankCommand();
rollbackCommand = blankCommand;
for (int i = 0; i < commandPairs; i++) {
offCommands[i] = blankCommand;
}
}
public void onButton(int buttonIndex, Command command) {
onCommands[buttonIndex] = command;
onCommands[buttonIndex].execute("on");
rollbackCommand = onCommands[buttonIndex];
}
public void offButton(int buttonIndex, Command command) {
offCommands[buttonIndex] = command;
offCommands[buttonIndex].execute("off");
rollbackCommand = offCommands[buttonIndex];
}
public void rollback(String state) {
rollbackCommand.rollback(state);
}
}