现在的位置: 首页 > 自动控制 > 工业·编程 > 正文

代码版设计模式14:策略模式【行为型】

2013-03-03 12:16 工业·编程 ⁄ 共 741字 ⁄ 字号 暂无评论

#include <iostream>
using namespace std;

//
struct ITravelWay
{
public:
    virtual ~ITravelWay() { }

    virtual void Travel() = 0;
};

class CTrainWay : public ITravelWay
{
public:
    virtual ~CTrainWay() { }

    virtual void Travel() { cout<<"Travel by train."<<endl; }
};

class CAirplaneWay : public ITravelWay
{
public:
    virtual ~CAirplaneWay() { }

    virtual void Travel() { cout<<"Travel by airplane."<<endl;  }
};

class CBicycleWay : public ITravelWay
{
public:
    virtual ~CBicycleWay() { }

    virtual void Travel() { cout<<"Travel by bicycle."<<endl; }
};

class CTravel
{
public:
    void Travel(ITravelWay *travelWay) { travelWay->Travel(); }
};

//
void main()
{
    CTravel travel;

    CTrainWay train;
    travel.Travel(&train);

    CAirplaneWay airplane;
    travel.Travel(&airplane);

    CBicycleWay bicycle;
    travel.Travel(&bicycle);
   
}

给我留言

留言无头像?