命令模式代码示例
2015-06-01 14:46
344 查看
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; } @Override public void execute() { // TODO Auto-generated method stub myTv.changeChannel( channel ); } }
package com.example.mingling; /** * 关机命令 * @author Administrator * */ public class CommandOff implements Command { private Tv myTv; public CommandOff( Tv tv ) { myTv = tv; } @Override public void execute() { // TODO Auto-generated method stub myTv.turnoff(); } }
package com.example.mingling; public class CommandOn implements Command { private Tv myTv; public CommandOn( Tv tv ) { myTv = tv; } @Override public void execute() { // TODO Auto-generated method stub myTv.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
相关文章推荐
- C++ 9.1.2 容器内元素的类型约束-------非引用、非IO标准库类型
- 《实战Java虚拟机》参加京东买200-100的活动,又可以买很多好书了
- java.util.concurrent-------TimeUnit
- Java Web - Struts2基本执行流程
- OC视频笔记3.10(可变数组的常用方法)3.12,3.13练习(略)(OC里description就是java里toString)
- C#使用System.Environment操作系统环境变量的中文API
- java串口编程
- 在eclipse程序中设置的断点上有一个斜杠,正常启动debug不能够跳转到debug页面,怎么解决
- IIC 针对EEPROM的驱动代码
- 浅谈C++多态性
- OC语言疯狂讲义学习笔记
- java.lang.OutOfMemoryError: Java heap space
- Asp.net框架
- java.lang.ClassFormatError
- python-sqlite3
- 由于代码已经过优化或者本机框架位于调用堆栈之上,无法计算表达式的值。
- PHP常用输出语句区别
- 演练:Office 编程(C# 和 Visual Basic)
- C#6.0 VS2015
- C++程序设计 - Week 1 从C走进C++