命令模式代码示例
来源:互联网 发布:骑马与砍杀设置优化 编辑:程序博客网 时间: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
- 命令模式代码示例
- 命令模式详解及示例代码演示
- 命令模式示例1
- 命令模式示例2
- 工厂模式示例代码
- 原型模式示例代码
- 原型模式代码示例
- 合成模式代码示例
- 适配器模式代码示例
- 观察者模式示例代码
- 代理模式代码示例
- Builder 设计模式 代码示例
- 装饰者模式示例代码
- 抽象工厂模式示例代码
- 策略模式-应用代码示例
- JAVA设计模式示例代码
- 单例模式代码示例
- 单例模式代码示例
- Java Web - Struts2基本执行流程
- RS485通信
- Support Vector Mechine
- Nginx安装google_perftools模块的方法
- 继承PreferenceActivity,报需要验证fragment是否有效
- 命令模式代码示例
- Tomcat配置虚拟目录、多域名、多个Http监听端口的方式
- C++ 9.1.2 容器内元素的类型约束-------非引用、非IO标准库类型
- RevitAPI: 如何创建云线?How to create RevisionCloud
- 如何调试PHP程序(转)
- android入门:zxing学习笔记(二)
- Qt 之 stylesheet 用法, QSS实例
- 《超实用的JavaScript代码段》可以参加京东买200-100的促销了
- android入门:zxing学习笔记(一)