行为模式
Stragegy,定义所有支持的算法的公共接口
ConcreteStrategy,封装了具体的算法或行为,继承于Strategy
Context,用一个ConcreteStrategy来配置,维护一个对Strategy对象的引用
使用场景:一系列算法(完成相同的工作),但是实现方法不一样。可以使用同一方法调用所有的算法。
下面是未使用设计模式的代码
class CBird
{
public:
virtual void Fly() { cout << "Flying"; }
};
class CParrot : public CBird
{
public:
void Fly()
{ CBird::Fly(); }
};
class CCock : public CBird
{
public:
void Fly() { cout << "Not flying"; }
};
使用Strategy设计模式后
// Strategy类
class FlyClass
{
public:
virtual void Fly() = 0;
};
// ConcreteStrategy类
class FlyNot : public FlyClass
{
public:
void Fly() { cout << "Not flying"; }
};
class FlyWings : public FlyClass
{
public:
void Fly() { cout << "Flying using wings"; }
};
// Context类
class CBird
{
public:
CBird(FlyClass* p) : m_pFly(p)
//...
void DoFly() { m_pFly->Fly(); }
private:
FlyClass* m_pFly;
};
// main
FlyClass* pFly = new FlyWings();
FlyClass* pFlyNot = new FlyNot();
CBird* pBird = new CBird(pFy);
pBird->DoFly();
CBird* pCock = new CBird(pFlyNot);
pCock->DoFly();