jeudi 17 mai 2018

Fill map in Command pattern

#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;
}

I have access violation in command->execute(a, b); , because map contains only null pointer, after filling. What is right way to store and filling map? I think I should use factory for creating classes, but even in this case I must to fill map, and I not very want to use global variable for saving map. Maybe any good idea about this code?

Aucun commentaire:

Enregistrer un commentaire