MultiThread/pattern/src/main/java/cn/bunny/pattern5/demo3/CommandDemo.java

59 lines
1.1 KiB
Java
Raw Normal View History

2025-02-01 20:32:09 +08:00
package cn.bunny.pattern5.demo3;
import lombok.Setter;
2025-02-01 20:32:09 +08:00
public class CommandDemo {
public static void main(String[] args) {
Receiver receiver = new Receiver();
2025-02-01 20:32:09 +08:00
ConcreteCommand concreteCommand = new ConcreteCommand(receiver);
2025-02-01 20:32:09 +08:00
Invoker invoker = new Invoker();
invoker.setCommand(concreteCommand);
invoker.invoke();
2025-02-01 20:32:09 +08:00
}
// 命令接口
interface Command {
2025-02-01 20:32:09 +08:00
/**
* 执行方法
2025-02-01 20:32:09 +08:00
*/
void execute();
}
2025-02-01 20:32:09 +08:00
// 接受者
static class Receiver {
public void action() {
System.out.println("接受者 执行。。。");
2025-02-01 20:32:09 +08:00
}
}
// 具体的执行命令
static class ConcreteCommand implements Command {
2025-02-01 20:32:09 +08:00
private final Receiver receiver;
2025-02-01 20:32:09 +08:00
public ConcreteCommand(Receiver receiver) {
this.receiver = receiver;
2025-02-01 20:32:09 +08:00
}
/**
* 执行方法
2025-02-01 20:32:09 +08:00
*/
@Override
public void execute() {
receiver.action();
2025-02-01 20:32:09 +08:00
}
}
@Setter
static class Invoker {
private Command command;
2025-02-01 20:32:09 +08:00
public void invoke() {
command.execute();
2025-02-01 20:32:09 +08:00
}
}
}