设计模式之六:命令模式(简单实现(餐厅点餐模拟流程))
工程名称:
命令接口:CommandInSimple 下载目录:http://www.cnblogs.com/jrsmith/admin/Files.aspx ,CommandInSimple.zip
1 package com.jyu.command; 2 3 /**命令接口*/ 4 public interface Command { 5 6 public void execute(); 7 }
打开电灯的具体命令对象:
1 package com.jyu.command; 2 3 public class LightOnCommand implements Command { 4 5 Light light; 6 7 public LightOnCommand(Light light) { 8 this.light = light; 9 } 10 11 @Override 12 public void execute() { 13 light.on(); 14 } 15 16 }
遥控器:
1 package com.jyu.command; 2 3 public class RemoteCOntrolTest { 4 5 /** 6 * @param args 7 */ 8 public static void main(String[] args) { 9 10 SimpleRemoteControl remote = new SimpleRemoteControl(); 11 Light light = new Light(); 12 LightOnCommand lightOn = new LightOnCommand(light); 13 14 remote.setCommand(lightOn); 15 remote.buttonWasPressed(); 16 } 17 18 }
利用遥控器开灯的简单测试:
1 package com.jyu.command; 2 3 /**遥控器*/ 4 public class SimpleRemoteControl { 5 6 Command slot; 7 8 public SimpleRemoteControl() { } 9 10 public void setCommand(Command command) { 11 this.slot = command; 12 } 13 14 public void buttonWasPressed(){ 15 slot.execute(); 16 } 17 18 }
1 package com.jyu.command; 2 3 public class Light { 4 5 public void on(){ 6 System.out.println("The Light is on..."); 7 } 8 9 public void off(){ 10 System.out.println("The Light is off..."); 11 } 12 }