命令模式
就是老板叫一个传话的(AssignCommand) 让他传递各种命令(Command),每个命令都有对应的执行人Receiver
传话的,传话的目的是这个命令能否执行成功,不关注谁执行,
public static void main(String[] args) {
AssignCommand assignCommand = new AssignCommand();//调用者
Command command = new ConcreteCommand();//执行的命令(生成的同时,也生成了receiver)
assignCommand.setCommand(command);//调用者拿到命令
assignCommand.assignCommand();//调用者执行命令(内部让receiver执行)
}
调用者及客户端
public class AssignCommand {
private Command command;//收到的命令
public void assignCommand(){
command.execute();
}
public void setCommand(Command command){
this.command = command;
}
}
执行的命令
//命令必须要有执行者
public abstract class Command {
protected final Receiver receiver;
protected Command(Receiver receiver) {
this.receiver = receiver;
}
public abstract void execute();
}
class ConcreteCommand extends Command{
//具体命令指定接收者
protected ConcreteCommand() {
super(new ConcreteReceiver());
System.out.println("准备好命令和接收人");
}
@Override
public void execute() {
super.receiver.doSomething();
}
}
任务执行者
public abstract class Receiver {
public abstract void doSomething();
}
//可能会有不同类型的任务
class ConcreteReceiver extends Receiver{
@Override
public void doSomething() {
System.out.println("执行者执行任务");
}
}
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 fulndon@qq.com