行为模式:Command(命令)
2013-02-07 20:42
399 查看
/* The Command interface */ public interface Command { void execute(); } import java.util.List; import java.util.ArrayList; /* The Invoker class */ public class Switch { private List<Command> history = new ArrayList<Command>(); public Switch() { } public void storeAndExecute(Command cmd) { this.history.add(cmd); // optional cmd.execute(); } } /* The Receiver class */ public class Light { public Light() { } public void turnOn() { System.out.println("The light is on"); } public void turnOff() { System.out.println("The light is off"); } } /* The Command for turning on the light - ConcreteCommand #1 */ public class FlipUpCommand implements Command { private Light theLight; public FlipUpCommand(Light light) { this.theLight = light; } public void execute(){ theLight.turnOn(); } } /* The Command for turning off the light - ConcreteCommand #2 */ public class FlipDownCommand implements Command { private Light theLight; public FlipDownCommand(Light light) { this.theLight = light; } public void execute() { theLight.turnOff(); } } /* The test class or client */ public class PressSwitch { public static void main(String[] args){ Light lamp = new Light(); Command switchUp = new FlipUpCommand(lamp); Command switchDown = new FlipDownCommand(lamp); Switch s = new Switch(); try { if (args[0].equalsIgnoreCase("ON")) { s.storeAndExecute(switchUp); } else if (args[0].equalsIgnoreCase("OFF")) { s.storeAndExecute(switchDown); } else { System.out.println("Argument \"ON\" or \"OFF\" is required."); } } catch (Exception e) { System.out.println("Arguments required."); } } }
相关文章推荐
- 行为设计模式---命令模式(Command)
- 命令模式(Command)----行为笔记
- 【设计模式】行为模式之Command命令
- 命令模式(Command Action 事务模式 对象行为模式)
- 设计模式-行为设计模式:命令模式 Command
- 【设计模式学习笔记十五】【行为模式】【命令模式(Command)】
- 行为模式之命令模式(Command Pattern)C++实现
- Java设计模式(20)——行为模式之命令模式(Command)
- 命令模式(Command)----行为笔记
- (行为模式)Command——命令模式
- 行为类模式(二):命令(Command)
- 【设计模式基础】行为模式 - 4 - 命令(Command)
- 设计技巧16:命令模式 Command 将请求封装成对象,传递行为
- c++ 设计模式之命令(Command)模式
- 21.命令模式--Command
- 我所理解的设计模式——对象行为之命令(Comand)模式
- 设计模式读书笔记之命令模式(Command Pattern)
- 命令模式(Command)
- 设计模式 - 命令模式(command pattern) 撤销(undo) 详解
- 行为型---命令模式(Command Pattern)