- 命令接收者接口或抽象定义
public interface IReceiver {
void doSomething();
}
- 命令接收者接口或抽象定义实现类
public class ConcreteReceiver implements IReceiver {
@Override
public void doSomething() {
//具体业务逻辑处理
}
}
- 命令接口或抽象定义
public interface ICommand {
void execute();
}
- 命令接口或抽象定义实现类
public class ConcreteCommand implements ICommand {
private IReceiver receiver;
public ConcreteCommand(IReceiver receiver) {
this.receiver = receiver;
}
@Override
public void execute() {
this.receiver.doSomething();
}
}
- 命令调用者
public class Invoker {
private ICommand command;
public void setCommand(ICommand command){
this.command = command;
}
public void action(){
this.command.execute();
}
}
- 场景使用
//命令调用者
Invoker invoker = new Invoker();
//命令接收者
IReceiver receiver = new ConcreteReceiver();
//命令
ICommand command = new ConcreteCommand(receiver);
//执行命令
invoker.setCommand(command);
invoker.action();