命令模式Command Pattern C++

来源:互联网 发布:apache基金会如何赚钱 编辑:程序博客网 时间:2024/05/23 22:39

命令模式:将请求的发起者和执行者解耦。

class Command{public:    ~Command();    virtual void operator()()=0;    virtual Command * clone() const = 0;};

命令执行特定的行为,它是一个 函数对象,以保持函数执行状态。

class Button{public :    Button(const std::string &label)        : label_(label),cmd(0){}    void setCmd(const Command * newCmd)    {        Cmd *tmp = newCmd->clone();        delete cmd;        cmd = tmp;    }    void onClick() const    {        if(cmd) (*cmd)();    }private:    std::string label_;    Command *cmd;};       

按钮与对应的命令绑定在一起。

特定动作执行:

class PlayMusic : public Command{public:    PlayMusic( const string & songFile ) : cons_(songFile){}    void operator()();    //  播放歌曲private:    MP3 song_;};
0 0
原创粉丝点击