命令模式代码示例

来源:互联网 发布:骑马与砍杀设置优化 编辑:程序博客网 时间:2024/05/16 18:54
package com.example.mingling;/** * //执行命令的接口 * @author Administrator * */public interface Command{void execute();}
package com.example.mingling;/** * 频道切换命令 * @author Administrator * */public class CommandChange implements Command{private Tv myTv;private int channel;public CommandChange(Tv tv ,int channel ){myTv = tv;this.channel = channel;}@Overridepublic void execute(){// TODO Auto-generated method stubmyTv.changeChannel( channel );}}

package com.example.mingling;/** * 关机命令 * @author Administrator * */public class CommandOff implements Command{private Tv myTv;public CommandOff(Tv tv ){myTv = tv;}@Overridepublic void execute(){// TODO Auto-generated method stubmyTv.turnoff();}}

package com.example.mingling;public class CommandOn implements Command{private Tv myTv;public CommandOn(Tv tv ){myTv = tv;}@Overridepublic void execute(){// TODO Auto-generated method stubmyTv.turnOn();}}

package com.example.mingling;public class Control{private Command onCommand , offCommand , changeChannel;public Control(Command on ,Command off ,Command channel ){onCommand = on;offCommand = off;changeChannel = channel;}public void turnOn(){onCommand.execute();}public void turnoff(){offCommand.execute();}public void changeChannel(){changeChannel.execute();}}

package com.example.mingling;/** * 命令接收者   * @author Administrator * */public class Tv{public int currentChannel = 0;public void turnOn(){System.out.println( "The televisino is on." );}public void turnoff(){System.out.println( "The televisino is off" );}public void changeChannel(int channel ){this.currentChannel = channel;System.out.println( "Now TV channel is " + channel );}}


package com.example.mingling;public class Client{public static void main(String[] args ){// 命令接收者Tv myTv = new Tv();// 开机命令CommandOn on = new CommandOn( myTv );// 关机命令CommandOff off = new CommandOff( myTv );// 频道切换命令CommandChange channel = new CommandChange( myTv , 2 );// 命令控制对象Control control = new Control( on , off , channel );// 开机control.turnOn();// 切换频道control.changeChannel();// 关机control.turnoff();}}


输出结果:

package com.example.mingling;




The televisino is on.
Now TV channel is 2
The televisino is off

0 0
原创粉丝点击