设计模式总结5--命令模式 commend pattern
命令模式把发出命令的责任和执行命令
的责任分割开,委派给不同的对象。就像我们去餐厅,点菜是找服务员,然后服务员去让厨师做菜
而不是我们直接找厨师做菜
public interface Commend { public void execute(); }
public class Remoter { public void click(Commend cmd){ cmd.execute(); } }
public class OpenLightCommend implements Commend{ private Light light; public OpenLightCommend(Light light){ this.light = light; } @Override public void execute() { light.open(); } }
测试
public class test { public static void main(String[] args) { /*命令的执行者light和命令的发出者remoter是分开的,靠着OpenLightCommend 连接*/ Light light = new Light(); OpenLightCommend olc = new OpenLightCommend(light); Remoter r = new Remoter(); r.click(olc); } }
===================================
===================================
宏命令:宏命令是命令的一种简单延伸,允许调用多个命令
public class MarcoCommend implements Commend{ private Commend[] cmds; public MarcoCommend(Commend... cmds){ this.cmds = cmds; } @Override public void execute() { for(Commend c : cmds){ c.execute(); } } }
public class test { public static void main(String[] args) { Light light = new Light(); OpenLightCommend olc = new OpenLightCommend(light); CloseLightCommend clc = new CloseLightCommend(light); MarcoCommend mc = new MarcoCommend(olc,clc); Remoter r = new Remoter(); r.click(mc); } }