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);
          }
       }
    }
    
  • 相关阅读:
    Git core objects
    各平台预定义的宏
    跨平台获取可执行文件的目录
    Windows、Linux、Mac OSX编译jni动态库
    xmpp整理笔记:发送图片信息和声音信息
    xmpp整理笔记:聊天信息的发送与显示
    xmpp整理笔记:用户网络连接及好友的管理
    小技巧,如何在Label中显示图片
    xmpp整理笔记:xmppFramework框架的导入和介绍
    xmpp整理笔记:环境的快速配置(附安装包)
  • 原文地址:https://www.cnblogs.com/zhangminghui/p/4214667.html
Copyright © 2011-2022 走看看