设计模式:Command

阅读更多
现在学习《Head First Design Pattern》,现在正看到第六章 the Command Pattern
我把书中的简单命令模式用D重写了一下,目的是大家共通学习!
import std.stdio;

/**
* 本程序是学习《Head First Design Pattern》做得程序,思想属于Head First
* 网址http://www.headfirstlabs.com/
* Authors:  Caoqi
* version: 0.001
* Date: April 15, 2007
*/
void SimpleCommand(){}


/**
* 命令的接口
*/
public interface Command {
        void execute();
}
/**
* 不执行命令的实现
*/
class NoCommand:Command{
        void execute() {}
}
/**
*
* 电灯类
*/
class Light {
        //String strMessage="";
        char[] strMessage="";
        /**
        * Params: strMessage = 消息
        *
        */
        this(char[] strMessage){
                this.strMessage=strMessage;
        }
        /**
        *  当电灯打开时进行显示
        */
        void on(){
                char[] str=this.strMessage;
                str~="  on";
                writefln(str);
        }
        /**
        * 当电灯关闭的时候显示
        */
        void off(){
                char[] str=this.strMessage;
                str~="  off";
                writefln(str);

        }
}
/**
* 开灯类
*/
class LightOnCommand:Command{
        Light light;
        this(Light light){
                this.light=light;
        }
        /**
        * 运行
        */
        void execute() {
                light.on();
        }

}

/**
* 开灯类
*/
class LightOffCommand:Command{
        Light light;
        this(Light light){
                this.light=light;
        }
        /**
        * 运行
        */
        void execute() {
                light.off();
        }

}

/**
* 简单远程控制类
*/
class SimpleRemoteControl {
        Command slot;///命令变量
        this() {
                // TODO Auto-generated constructor stub

        }
        /**
        * 设置要职行的命令
        * Params: command = 要执行的命令
        *
        */
        void setCommand(Command command){
                slot=command;
        }
        /**
        * 执行命令
        */
        void buttonWasPressed(){
                slot.execute();
                //return 1;
        }
}


/**
* 主程序
*/
/++++++++++++++++++++++++

  + Our function.

  + Example:

  + --------------------------

  +  import std.stdio;

  +
  +   void main(char[][] args) {
  +              SimpleRemoteControl remote=new SimpleRemoteControl();
  +              Light light=new Light("Light");
  +              LightOnCommand lightOn=new LightOnCommand(light);

  +              remote.setCommand(lightOn);
  +              remote.buttonWasPressed();
  + }

  + --------------------------

  +/
void main(char[][] args) {
        SimpleRemoteControl remote=new SimpleRemoteControl();
        Light light=new Light("Light");
        LightOnCommand lightOn=new LightOnCommand(light);


        remote.setCommand(lightOn);
        remote.buttonWasPressed();

        LightOffCommand lightOff=new LightOffCommand(light);
        remote.setCommand(lightOff);
        doStuff(&remote.buttonWasPressed);///此处练习delegate

}

void doStuff(void delegate() d) {
     d() ;
}

你可能感兴趣的:(设计模式,HTML)