//命令接收者publicclassTv{publicintcurrentChannel=0;publicvoidturnOn(){System.out.println("The televisino is on.");}publicvoidturnOff(){System.out.println("The television is off.");}publicvoidchangeChannel(intchannel){this.currentChannel=channel;System.out.println("Now TV channel is "+channel);}}//执行命令的接口publicinterfaceCommand{voidexecute();}//开机命令publicclassCommandOnimplementsCommand{privateTvmyTv;publicCommandOn(Tvtv){myTv=tv;}publicvoidexecute(){myTv.turnOn();}}//关机命令publicclassCommandOffimplementsCommand{privateTvmyTv;publicCommandOff(Tvtv){myTv=tv;}publicvoidexecute(){myTv.turnOff();}}//频道切换命令publicclassCommandChangeimplementsCommand{privateTvmyTv;privateintchannel;publicCommandChange(Tvtv,intchannel){myTv=tv;this.channel=channel;}publicvoidexecute(){myTv.changeChannel(channel);}}//可以看作是遥控器吧publicclassControl{privateCommandonCommand,offCommand,changeChannel;publicControl(Commandon,Commandoff,Commandchannel){onCommand=on;offCommand=off;changeChannel=channel;}publicvoidturnOn(){onCommand.execute();}publicvoidturnOff(){offCommand.execute();}publicvoidchangeChannel(){changeChannel.execute();}}//测试类publicclassClient{publicstaticvoidmain(String[]args){// 命令接收者TvmyTv=newTv();// 开机命令CommandOnon=newCommandOn(myTv);// 关机命令CommandOffoff=newCommandOff(myTv);// 频道切换命令CommandChangechannel=newCommandChange(myTv,2);// 命令控制对象Controlcontrol=newControl(on,off,channel);// 开机control.turnOn();// 切换频道control.changeChannel();// 关机control.turnOff();}}
执行结果为:
The televisino is on.
Now TV channel is 2
The television is off.