命令设计模式

来源:互联网 发布:达瓦黑钢凛怎数据 编辑:程序博客网 时间:2024/06/10 21:58

引用原文http://www.cnblogs.com/devinzhang/archive/2012/01/06/2315235.html

文末举了一个模拟电视机操作,偶感觉,其中commandChange太过僵硬,必须new一个

对象才能切换频道。附上代码,自己写的部分很少很少

package command;class TV{public int currentChannel = 0;public void turnOn(){System.out.print("the televisino is on\n");}public void turnOff(){System.out.print("the televisino is off\n");}public void changleChannel(int channel){System.out.print("the televisino will changle to " + channel + "\n");this.currentChannel = channel;}}interface Command{void exeCute(int channel);}class CommandOn implements Command{private TV tv;CommandOn(TV tv){this.tv = tv;}public void exeCute(int channel){tv.turnOn();}}class CommandOff implements Command{private TV tv;CommandOff(TV tv){this.tv = tv;}public void exeCute(int channel){tv.turnOff();}}class CommandChange implements Command{private TV tv;CommandChange(TV tv){this.tv = tv;}public void exeCute(int channel){tv.changleChannel(channel);}}class Control{private Command commandOn, commandOff, commandChange;public Control(Command commandOn, Command commandOff, CommandChange commandChange){this.commandOn = commandOn;this.commandOff = commandOff;this.commandChange = commandChange;}public void turnOn(){commandOn.exeCute(0);}public void turnOff(){commandOff.exeCute(0);}public void turnChange(int channel){commandChange.exeCute(channel);}}public class TvClient {public static void main(String[] args){TV tv = new TV();CommandOn commandOn = new CommandOn(tv);CommandOff commandOff = new CommandOff(tv);CommandChange commandChange = new CommandChange(tv);Control control = new Control(commandOn, commandOff, commandChange);control.turnOn();control.turnOff();int channel = 12;control.turnChange(channel);}}


原创粉丝点击