命令模式将命令调用者与命令执行者解耦,有效降低系统的耦合度。同时,由于命令调用者和命令执行者进行了解耦,所以增加和删除命令变得非常方便。
(1)定义Command接口
public interface Command{ public void exe(String command); }
(2)定义Command实现类
public class ConcreteCommand implements Command{ private Receiver receiver; public ConcreteCommand(Receiver receiver){ this.receiver = receiver; } @Override public void exe(String command){ receiver.action(command); } }
(3)定义命令调用者
public class Invoker{ private final static Log logger = LogFactory.getLog(this.getClass()); private Command command; public Invoker(Command command){ this.command = command; } public void action(String commandMessage){ logger.info("command sending..."); command.exe(commandMessage); } }
(4)定义命令接收者
public class Receiver{ private final static Log logger = LogFactory.getLog(this.getClass()); public void action(String command){ logger.info("command received"); } }
(5)使用命令模式
public static void main(String args){ Receiver receiver = new Receiver(); Command cmd = new ConcreteCommand(receiver); Invoker invoker = new Invoker(cmd); invoker.action("cmd1"); }