mardi 4 septembre 2018

Strategy Pattern, why it need a extra class to manage strategy class

I am learning the strategy pattern, I wonder what is the Class context’s purpose? it seems makes these code even complex, thanks for your help. //*************************************************************************************************//

class Strategy
{
public:
    virtual void excute();
};
class S1 : public Strategy
{
public:
    virtual void excute() 
    {
        //*******s1
    }
};

class S2 : public Strategy
{
public:
    virtual void excute()
    {
        //*******s2
    }
};

class Context 
{
private:
    Strategy* s;
public:
    Context(Strategy *s)
    {
        this->s = s;
    }
    void executeStrategy() 
    {
        s->excute();
    }
};

int main()
{
    //******classic style, (pls ignore memory issue)****************************
    Context* c= new Context(new S1());
    c->executeStrategy();

    c =new Context(new S2());
    c->executeStrategy();


    //*****why does it need a extra class Context ,rather than use the follwing code********************
    Strategy* s = new S1();
    s->excute();

    s = new S2();
    s->excute();
    //************************
}

Aucun commentaire:

Enregistrer un commentaire