设计模式学学习 — 策略模式

策略模式定义

定义一系列算法,将每个算法封装起来,而且使它们可以互相替换。策略模式让算法独立于使用它的客户而独立变化

详细理论参考:

https://design-patterns.readthedocs.io/zh_CN/latest/behavioral_patterns/strategy.html

简单案例实现

假如现在你要去北京,有多种交通方式可以选择,汽车、飞机、高铁,当然牛逼的话也可以选择自行车或走路。这里不同的交通方式就是不同的策略

//抽象的交通策略
class AbstractTrafficStrategy{
     
public:
    virtual void ride(void) = 0;
};

//飞机交通策略
class AirplaneStrategy :public AbstractTrafficStrategy{
     
public:
    void ride()
    {
     
        cout << "坐飞机" << endl;
    }
};

//高铁交通策略
class TrainStrategy : public AbstractTrafficStrategy{
     
public:
    void ride()
    {
     
        cout << "坐高铁" << endl;
    }
};

//汽车交通策略
class CarStrategy : public AbstractTrafficStrategy{
     
public:
    void ride()
    {
     
        cout << "开车" << endl;
    }
};

//交通策略工厂
class TrafficStrategyFactory{
     
public:
    AbstractTrafficStrategy *createTrafficStrategy(string traffic)
    {
     
        if (traffic == "飞机")
        {
     
            return new AirplaneStrategy;
        }
        else if (traffic == "高铁")
        {
     
            return new TrainStrategy;
        }
        else if (traffic == "汽车")
        {
     
            return new CarStrategy;
        }
    }
};

class Person
{
     
public:
    void selectTraffic(AbstractTrafficStrategy *traffic) //选择策略
    {
     
        mTraffic = traffic;
    }
    void go()   //执行策略
    {
     
        mTraffic->ride();
    }
private:
    AbstractTrafficStrategy *mTraffic;
};

int main()
{
     
    TrafficStrategyFactory *aTrafficStategyFac = new TrafficStrategyFactory;
    Person *Zhangsan =  new Person;

    AbstractTrafficStrategy *trafficStrategy = aTrafficStategyFac->createTrafficStrategy("高铁");
    Zhangsan->selectTraffic(trafficStrategy);
    Zhangsan->go();

    trafficStrategy = aTrafficStategyFac->createTrafficStrategy("飞机");
    Zhangsan->selectTraffic(trafficStrategy);
    Zhangsan->go();

    trafficStrategy = aTrafficStategyFac->createTrafficStrategy("汽车");
    Zhangsan->selectTraffic(trafficStrategy);
    Zhangsan->go();

    delete Zhangsan;
    delete aTrafficStategyFac;
    delete trafficStrategy;

    return 0;
}

你可能感兴趣的:(设计模式)