c ++中策略模式所需的指导

时间:2015-01-02 06:19:24

标签: c++

我已经研究过策略模式,并且在我提到的pdf中给出的例子中理解了它。我想确保我的理解是正确的。所以我用C ++编写了一个简单的程序,并以家庭和车辆为主题设计了战略模式。 请提供对该计划的更正/建议。这将是非常有用的。

#include <iostream>

class Vehicle
{
public:
    virtual void useVehicle() = 0;
};

class FordFigo : public Vehicle
{
public:
    void useVehicle()
    {
        std::cout << "Driving FordFigo" << std::endl;
    }
};

class TataNano : public Vehicle
{
public:
    void useVehicle()
    {
        std::cout << "Driving TataNano" << std::endl;
    }
};

class BlackPulsar : public Vehicle
{
public:
    void useVehicle()
    {
        std::cout << "Riding BlackPulsar" << std::endl;
    }
};

class HondaActiva : public Vehicle
{
public:
    void useVehicle()
    {
        std::cout << "Riding HondaActiva" << std::endl;
    }
};

class Family
{
public:
    Vehicle *myVehicle;
    virtual void display() = 0;
    void setVehicle(Vehicle *v)
    {
        myVehicle = v;
    }
    void driveVehicle()
    {
        myVehicle->useVehicle();
    }
};

class Father : public Family
{
public:
    virtual void display()
    {
        std::cout << "I am Father" << std::endl;
    }
};

class Mother : public Family
{
public:
    virtual void display()
    {
        std::cout << "I am Mother" << std::endl;
    }
};


class Son : public Family
{
public:
    virtual void display()
    {
        std::cout << "I am Son" << std::endl;
    }
};


class Daughter : public Family
{
public:
    virtual void display()
    {
        std::cout << "I am Daughter" << std::endl;
    }
};

int main()
{
    Family *fam = new Father();
    fam->display();
    fam->setVehicle(new FordFigo());
    fam->driveVehicle();

    fam = new Daughter();
    fam->display();
    fam->setVehicle(new HondaActiva());
    fam->driveVehicle();
    return 0;
}

0 个答案:

没有答案