命令模式_命令也是类(命令的发起人和执行人分离)
/**
* 命令抽象类
* @author maikec
* 2019/5/20
*/
public abstract class AbstractCommand {
protected final AbstractReceiver receiver;
public AbstractCommand(AbstractReceiver receiver){
this.receiver = receiver;
}
/**
* 命令1
*/
public abstract void execute();
/**
* 命令2
*/
public abstract void execute1();
}
/**
* 命令执行者抽象类
* @author maikec
* 2019/5/20
*/
public abstract class AbstractReceiver {
/**
* 命令接收
*/
public abstract void action();
}
/**
* 命令调用抽象类
* @author maikec
* 2019/5/20
*/
public abstract class AbstractInvoker {
protected final AbstractCommand command;
public AbstractInvoker(AbstractCommand command){
this.command = command;
}
/**
* 调用命令接口
*/
public abstract void invoke();
}
/**
* @author maikec
* 2019/5/20
*/
public class ConcreteCommand extends AbstractCommand {
public ConcreteCommand(AbstractReceiver receiver) {
super(receiver);
}
@Override
public void execute() {
System.out.println("starting command...");
receiver.action();
System.out.println("end command...");
}
@Override
public void execute1() {
throw new UnsupportedOperationException();
}
}
/**
* @author maikec
* 2019/5/20
*/
public class ConcreteInvoker extends AbstractInvoker {
public ConcreteInvoker(AbstractCommand command) {
super(command);
}
@Override
public void invoke() {
System.out.println("start invoke command...");
command.execute();
System.out.println("end invoke command...");
}
}
/**
* 具体命令执行人
* @author maikec
* 2019/5/20
*/
public class ConcreteReceiver extends AbstractReceiver {
@Override
public void action() {
System.out.println("ConcreteReceiver");
}
}
/**
* @author maikec
* 2019/5/20
*/
public class CommandDemo {
public static void main(String[] args) {
AbstractReceiver receiver = new ConcreteReceiver();
AbstractCommand command = new ConcreteCommand(receiver);
AbstractInvoker invoker = new ConcreteInvoker(command);
invoker.invoke();
}
}
复制代码
附录
github.com/maikec/patt… 个人GitHub设计模式案例
声明
引用该文档请注明出处