设计模式之命令模式(c++)

命令模式的作用是将函数转换为对象,将实际的操作与并行的框架分离,命令模式属于行为级

类图如下:


代码来源于c++编程思想

class Task {
public:
    virtual void operation() = 0;
};
class TaskRunner {              //singleton pattern
    static vector<Task*> tasks;
    TaskRunner() {}
    TaskRunner& operator=(TaskRunner&);
    TaskRunner(const TaskRunner&);
    static TaskRunner tr;
public:
    static void add(Task& t) { tasks.push_back(&t); }
    static void run() {
        vector<Task*>::iterator it = tasks.begin();
        while (it != tasks.end())
            (*it++)->operation();
    }
};

TaskRunner TaskRunner::tr;      //init static member (non-int)
vector<Task*> TaskRunner::tasks;

class EventSimulator {
    clock_t creation;
    clock_t delay;
public:
    EventSimulator() : creation(clock()) {
        delay = CLOCKS_PER_SEC/4 * (rand()%20 + 1);
        cout << "delay = " << delay << endl;
    }
    bool fired() {
        return clock() > creation + delay;
    }
};

class Button {
    bool pressed;
    string id;
    EventSimulator e;
public:
    Button(string name) : id(name), pressed(false) {}
    void press() { pressed = true; }
    bool isPressed() {
        if (e.fired()) press();
        return pressed;
    }
    friend ostream&
    operator<<(ostream& os, const Button& b) {
        return os << b.id;
    }
};

class CheckButton : public Task {
    bool handled;
    Button button;
public:
    CheckButton(Button& b) : button(b), handled(false) {}
    void operation() {
        if (!handled && button.isPressed()) {
            cout << button << "pressed" << endl;
            handled = true;
        }
    }
};

void procedure() {
    TaskRunner::run();
}

void CommandPatternTest()
{
    srand(time(0));
    Button b1("B1"), b2("B2"), b3("B3");
    CheckButton cb1(b1), cb2(b2), cb3(b3);
    TaskRunner::add(cb1);
    TaskRunner::add(cb2);
    TaskRunner::add(cb3);
    while (true)
    {
        procedure();
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值