java23中设计模式之命令模式
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.bdqn.command; /** * * @author OU * */ public interface Command { //这个方法是一个返回结果为空的放大 实际项目中,可以根据需求设计多个不同的方法 void execute(); } class ConcreteCommand implements Command{ //命令的真正的执行者 private Receiver receiver; public ConcreteCommand(Receiver receiver) { super(); this.receiver = receiver; } public void execute() { //命令真正执行前或后,执行相关的操作 receiver.action(); } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.bdqn.command; /** * 真正的命令执行者 * @author OU * */ public class Receiver { public void action(){ System.out.println("Receiver.action"); } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.bdqn.command; /** * 调用者 * @author OU * */ public class Invoke { //也可以通过容器list<command> 可以容纳很多命令对象,进行批处理,数据库底层的事务管理就是类似的结构 private Command command; public Invoke(Command command) { super(); this.command = command; } //业务方法,用于调用命令类的方法 public void call(){ command.execute(); } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.bdqn.command; public class Client { public static void main(String[] args) { Command c=new ConcreteCommand(new Receiver()); Invoke i=new Invoke(c); i.call(); } }