zoukankan      html  css  js  c++  java
  • [译]Java 设计模式之命令

    (文章翻译自Java Design Pattern: Command)

    命令设计模式在进行执行和记录的时候需要一个操作及其参数和封装在一个对象里面。在下面的例子中,命令是一个操作,它的参数是一个Computer,而且他们被封装在一个Switch中。

    从另外一个视角来看,命令模式有四个部分:command,recevier,invoker和client。在这个例子中,Switch是invoker,Computer是receiver。一个具体的Command需要一个receiver对象而且调用receiver的方法。invok儿使用不同的具体Command。Client决定对于receiver去使用哪个command.

    命令设计模式类图

    command-design-pattern

    Java命令模式例子

    package designpatterns.command;
     
    import java.util.List;
    import java.util.ArrayList;
     
    /* The Command interface */
    interface Command {
       void execute();
    }
     
    // in this example, suppose you use a switch to control computer
     
    /* The Invoker class */
     class Switch { 
       private List<Command> history = new ArrayList<Command>();
     
       public Switch() {
       }
     
       public void storeAndExecute(Command command) {
          this.history.add(command); // optional, can do the execute only!
          command.execute();        
       }
    }
     
    /* The Receiver class */
     class Computer {
     
       public void shutDown() {
          System.out.println("computer is shut down");
       }
     
       public void restart() {
          System.out.println("computer is restarted");
       }
    }
     
    /* The Command for shutting down the computer*/
     class ShutDownCommand implements Command {
       private Computer computer;
     
       public ShutDownCommand(Computer computer) {
          this.computer = computer;
       }
     
       public void execute(){
          computer.shutDown();
       }
    }
     
    /* The Command for restarting the computer */
     class RestartCommand implements Command {
       private Computer computer;
     
       public RestartCommand(Computer computer) {
          this.computer = computer;
       }
     
       public void execute() {
          computer.restart();
       }
    }
     
    /* The client */
    public class TestCommand {
       public static void main(String[] args){
          Computer computer = new Computer();
          Command shutdown = new ShutDownCommand(computer);
          Command restart = new RestartCommand(computer);
     
          Switch s = new Switch();
     
          String str = "shutdown"; //get value based on real situation
     
          if(str == "shutdown"){
        	  s.storeAndExecute(shutdown);
          }else{
        	  s.storeAndExecute(restart);
          }
       }
    }
    
  • 相关阅读:
    Cannot change network to bridged: There are no un-bridged host network adapters解决方法
    The authenticity of host 192.168.0.xxx can't be established.
    Vm下 linux与windowsxp文件共享的方法
    vmware 下的linux的host only上网配置
    VMWare三种工作模式 :bridge、host-only、nat
    云技术入门指导:什么是云计算技术,云技术用什么语言开发
    什么是移动云计算
    云计算是什么
    架构之路
    这首诗看着是越看越顺眼,百赋乐其中
  • 原文地址:https://www.cnblogs.com/zhangminghui/p/4214667.html
Copyright © 2011-2022 走看看