- #include <iostream>
- using namespace std;
- // 飞行行为接口类
- class FlyStrategy
- {
- public:
- virtual void Fly() = 0;
- protected:
- FlyStrategy(){}
- };
- // 高空飞行行为具现类
- class HeightFly:public FlyStrategy
- {
- public:
- static HeightFly &GetSingleton()
- {
- static HeightFly s_HeightFly;
- return s_HeightFly;
- }
- virtual void Fly()
- {
- cout << "It is a heightfly behavior." << endl;
- }
- private:
- HeightFly(){}
- };
- // 低空飞行行为具现类
- class LowFly:public FlyStrategy
- {
- public:
- static LowFly &GetSingleton()
- {
- static LowFly s_LowFly;
- return s_LowFly;
- }
- virtual void Fly()
- {
- cout << "It is a lowfly behavior." << endl;
- }
- private:
- LowFly(){}
- };
- // 叫声行为接口类
- class SoundStrategy
- {
- public:
- virtual void MakeSound() = 0;
- protected:
- SoundStrategy(){}
- };
- // 大声叫行为具现类
- class LoudlySound:public SoundStrategy
- {
- public:
- static LoudlySound &GetSingleton()
- {
- static LoudlySound s_LoudlySound;
- return s_LoudlySound;
- }
- virtual void MakeSound()
- {
- cout << "It is a loudlysound behavior." << endl;
- }
- private:
- LoudlySound(){}
- };
- // 小声叫行为具现类
- class SmallSound:public SoundStrategy
- {
- public:
- static SmallSound &GetSingleton()
- {
- static SmallSound s_SmallSound;
- return s_SmallSound;
- }
- virtual void MakeSound()
- {
- cout << "It is a smallsound behavior." << endl;
- }
- private:
- SmallSound(){}
- };
- // 鸭子具现类
- class Duck
- {
- private:
- // 行为接口
- FlyStrategy *m_pFlyStrategy;
- SoundStrategy *m_pSoundStrategy;
- public:
- // 带参数构造函数
- Duck(FlyStrategy *p_pFlyStrategy, SoundStrategy *p_pSoundStrategy):
- m_pFlyStrategy(p_pFlyStrategy),m_pSoundStrategy(p_pSoundStrategy){}
- // 飞行
- void Fly()
- {
- m_pFlyStrategy->Fly();
- }
- // 发出叫声
- void Sound()
- {
- m_pSoundStrategy->MakeSound();
- }
- // 动态设置行为接口
- void SetFlyStrategy(FlyStrategy *p_pFlyStrategy)
- {
- m_pFlyStrategy = p_pFlyStrategy;
- }
- void SetSoundStrategy(SoundStrategy *p_pSoundStrategy)
- {
- m_pSoundStrategy = p_pSoundStrategy;
- }
- // 显示虚函数
- virtual void Display() const
- {
- cout << "This is a ordinary duck." << endl;
- }
- };
- int main()
- {
- // 创建鸭子对象
- Duck duck(&HeightFly::GetSingleton(), &LoudlySound::GetSingleton());
- // 作出行为
- duck.Fly();
- duck.Sound();
- // 动态切换鸭子行为
- duck.SetFlyStrategy(&LowFly::GetSingleton());
- duck.SetSoundStrategy(&SmallSound::GetSingleton());
- // 作出新一轮的行为
- duck.Fly();
- duck.Sound();
- system("pause");
- return 0;
- }
- 策略模式理解:策略模式的核心理念是将类型中变换的部分(行为接口)分离到外部,并以特定的一组类对其进行实现,
- 而在原类型内部只保留各行为抽象基类接口的指针,通过委托的方式实现用户的请求并提供Setter函数方
- 便用户动态地改变行为的类型.
- 继承的缺点:白箱复用的特性导致子类默认继承一份缺省实现,将易变化的实现代码整合进类型定义将导致日后增加新
- 的实现或进行实现的修改尤为困难.每次当需要新的需求时都需要覆盖以前的实现,容易导致类泛滥,不能达到完
- 全的代码复用.
- 组合的优点:黑箱复用的方式不会暴露实现的细节,分离封装变化的部分增加可维护性和易扩展性,并带来完全的代码复用.
- 基于接口的编程使得可以动态的改变行为类型.
设计模式之策略模式
最新推荐文章于 2024-10-12 11:29:12 发布