在命令模式中填充地图

时间:2018-05-17 18:46:57

标签: c++ design-patterns

#include <map>

class ICommand
{
public:
    virtual double execute(double, double);
    ~ICommand();
};
class Add: public ICommand
{
public:
    double execute(double a, double b) override
    {
        return a + b;
    }
    double operator()(double a, double b){
        return a + b;
    }

};
class Sub : public ICommand
{
public:
    double execute(double a, double b) override
    {
        return a - b;
    }
    double operator()(double a, double b) {
        return a - b;
    }
};
class Mul : public ICommand
{
public:
    double execute(double a, double b) override
    {
        return a * b;
    }
    double operator()(double a, double b) {
        return a * b;
    }
};
class Div : public ICommand
{
public:
    double execute(double a, double b) override
    {
        return a / b;
    }
    double operator()(double a, double b) {
        return a / b;
    }
};

class RequestHundler
{
    std::map<int, ICommand*> commands;
    Add* add;
    Sub* sub;
    Mul* mul;
    Div* div;
public:
    RequestHundler()
    {
        commands[1] = add;
        commands[2] = sub;
        commands[3] = mul;
        commands[4] = div;
    }
    double HandleRequest(int action, double a, double b)
    {
        ICommand* command = commands[action];
        return  command->execute(a, b);
    }
};


int main(double argc, char* argv[])
{
    RequestHundler* handler = new RequestHundler();
    double result = handler->HandleRequest(2, 4, 6);
    return 0;
}

我在命令中有访问冲突 - >执行(a,b); ,因为map在填充后只包含空指针。什么是存储和填充地图的正确方法? 我想我应该使用工厂来创建类,但即使在这种情况下我必须填充地图,我不想非常想使用全局变量来保存地图。也许对这段代码有什么好主意?

0 个答案:

没有答案