命令模式把请求操作的对象和执行操作的对象解耦。
代码如下:
先写命令真正的执行者
public class Receiver { public void extA() { System.out.println("Command excA!!"); } public void extB() { System.out.println("Command excB!!"); } }
再写对命令的抽象
public abstract class Command { public Receiver rec=null; public void setRec(Receiver rec) { this.rec=rec; } public abstract void exc(); } public class CommandImpA extends Command { public void exc() { rec.extA(); } } public class CommandImpB extends Command{ public void exc() { rec.extB(); } }
然后是请求操作命令的类
public class Invoker { private ArrayList<Command> cmdList=new ArrayList<Command>(); public void setCommand(Command cmd) { this.cmdList.add(cmd); } public void exc() { for(Command cmd:cmdList) { cmd.exc(); } } }
最后写一个测试
public static void main(String[] args) { Command cmdA=new CommandImpA(); Command cmdB=new CommandImpB(); cmdA.setRec(new Receiver()); cmdB.setRec(new Receiver()); Invoker ivk=new Invoker(); ivk.setCommand(cmdA); ivk.setCommand(cmdB); ivk.setCommand(cmdB); ivk.setCommand(cmdA); ivk.setCommand(cmdA); ivk.setCommand(cmdA); ivk.exc(); }