深入理解C++之策略模式

2020-01-06 15:27:32丽君

声明 FlyBehavior 类型的指针,如此,只需通过指针 _pfB 便可调用相应的”算法“ -- ”飞行方式“


class Duck {
public:
  ...
private:
  FlyBehavior* _pfB; // 或 std::shared_ptr<FlyBehavior> _pfB;
};

3  策略模式

3.1  内容

即便不懂设计模式,只有严格按照上面的三个设计原则,则最后的设计思路也会和策略模式类似,可能只是一些细微处的差别

下面来看策略模式的具体内容和结构图:

Defines a family of algorithms,  encapsulates each one,  and makes them interchangeable.  Strategy lets the algorithm vary independently

from clients that use it.

  C++,策略模式

Context 指向 Strategy (由指针实现);Context 通过 Strategy 接口,调用一系列算法;ConcreteStrategy 则实现了一系列具体的算法

3.2  智能指针

上例中,策略模式的“接口” 对应于抽象基类 FlyBehavior,“算法实现”分别对应派生类 FlyWithWings, FlyNoWay, FlyWithRocket,“引用”对应 _pfB 指针

为了简化内存管理,可以将 _pfB 声明为一个“智能指针”,同时在 Duck 类的构造函数中,初始化该“智能指针”


Duck::Duck(std::shared_ptr<FlyBehavior> pflyBehavior) : _pfB(pflyBehavior) {}

直观上看, Duck 对应于 Context,但 Duck 基类并不直接通过 FlyBehavior 接口来调用各种“飞行方式” -- 即“算法”,实际是其派生类 MallardDuck,RedheadDuck 和RubberDuck,这样,就需要在各个派生类的构造函数中,初始化 _pfB


MallardDuck::MallardDuck(std::shared_ptr<FlyBehavior> pflyBehavior) : Duck(pflyBehavior) {}

 然后,在 Duck 基类中,通过指针 _pfB, 实现了对 fly 的调用


void Duck::performFly()
{
  _pfB->fly();
}