命令模式(C++)

#include 
using namespace std;

class action
{
public:
    action(){}
    ~action(){}
    void forward(){cout<<"forward"<<endl;}
    void backward(){cout<<"backward"<<endl;}
};

class command
{
public:
    command(){}
    virtual ~command(){}
    virtual void execute()=0;
    virtual void unexecute()=0;
};

class buttoncommand : public command
{
public:
    buttoncommand(){}
    virtual ~buttoncommand(){}
    void execute(){act->forward();}
    void unexecute(){act->backward();}

private:
    action *act;
};

class Switch
{
public:
    Switch():cmd(new buttoncommand){}
    ~Switch(){}
    void open(){cmd->execute();}
    void close(){cmd->unexecute();}
private:
    command *cmd;
};

int main()
{
    Switch *sw=new Switch;
    sw->open();
    sw->close();
    delete sw;

    system("pause");
    return 0;
}

转载于:https://www.cnblogs.com/tiandsp/archive/2012/06/27/2565732.html

你可能感兴趣的:(命令模式(C++))