import java.util.ArrayList;
import java.util.List;
/**
* 命令模式
* 类型: 行为型
* 描述: 将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持撤销和恢复功能
*/
public class CommandMode {
// 命令接收者
public static class Receiver {
public void action() {
System.out.println("Receiver action");
}
}
// 命令
public static class ConcreteCommand implements Command {
private Receiver receiver;
public ConcreteCommand(Receiver receiver) {
this.receiver = receiver;
}
public void execute() {
receiver.action();
}
}
// 命令接口
public static interface Command {
void execute();
}
// 接收者接口
public interface LightReceiver {
void turnOn();
void turnOff();
}
public static class LightOnCommand implements Command {
private LightReceiver lightReceiver;
public LightOnCommand(LightReceiver lightReceiver) {
this.lightReceiver = lightReceiver;
}
@Override
public void execute() {
lightReceiver.turnOn();
}
}
public static class LightOffCommand implements Command {
private LightReceiver lightReceiver;
public LightOffCommand(LightReceiver lightReceiver) {
this.lightReceiver = lightReceiver;
}
@Override
public void execute() {
lightReceiver.turnOff();
}
}
// 具体接收者类
public static class SimpleLight implements LightReceiver {
@Override
public void turnOn() {
System.out.println("Light is on.");
}
@Override
public void turnOff() {
System.out.println("Light is off.");
}
}
// 调用者
public static class RemoteControl {
private List<Command> commands = new ArrayList<>();
public void setCommand(int slot, Command command) {
commands.set(slot, command);
}
public void pressButton(int slot) {
commands.get(slot).execute();
}
}
// 命令调用者
public static class Invoker {
private Command command;
public Invoker(Command command) {
this.command = command;
}
public void action() {
command.execute();
}
}
public static void main(String[] args) {
// 创建接收者
Receiver receiver = new Receiver();
// 创建命令
Command command = new ConcreteCommand(receiver);
// 创建调用者
Invoker invoker = new Invoker(command);
// 执行命令
invoker.action();
}
}
设计模式-行为型-命令模式
于 2024-04-26 11:03:35 首次发布