定义:
策略模式定义了算法族,分别封装起来,让他们之间可以相互替换,此模式让算法的变化独立于使用算法的客户。
场景:
鸭子种类繁多,有野鸭子、橡皮鸭、诱饵鸭,他们有的会飞,有的不会飞,有的会吱吱叫,有的会呱呱叫,有的还不会叫。其中的飞行行为和呱呱叫行为就可以当做算法族封装起来,这样鸭子的飞行行为或呱呱叫行为就可以相互替换了,如果鸭子翅膀受伤了,我们就可以改变鸭子的飞行行为,让其不会飞。
类图:
c++代码如下:
#include <iostream>
using namespace std;
class FlyBehavior
{
public:
virtual void fly() = 0;
};
class FlyWithWings:public FlyBehavior
{
public:
void fly()
{
printf("I'm flying!!\n");
}
};
class FlyNoWay:public FlyBehavior
{
public:
void fly()
{
printf("I can't fly\n");
}
};
class QuackBehavior
{
public:
virtual void quack() =0;
};
class Quack:public QuackBehavior
{
public:
void quack()
{
printf("Quack\n");
}
};
class MuteQuack:public QuackBehavior
{
public:
void quack()
{
printf("<<Silence>>\n");
}
};
class Squeak:public QuackBehavior
{
public:
void quack()
{
printf("Squeak\n");
}
};
class Duck
{
public:
virtual ~Duck()
{
delete m_pFlyBehavior;
delete m_pQuackBehavior;
}
virtual void display() = 0;
void performFly()
{
if (NULL !=m_pFlyBehavior)
{
m_pFlyBehavior->fly();
}
}
void perfromQuack()
{
if (NULL != m_pQuackBehavior)
{
m_pQuackBehavior->quack();
}
}
void swim()
{
printf("All ducks float,even decoys!\n");
}
void setFlyBehavior(FlyBehavior* fb)
{
if (NULL != m_pFlyBehavior)
{
delete m_pFlyBehavior;
}
m_pFlyBehavior = fb;
}
void setQuackBehavior(QuackBehavior* qb)
{
if (NULL != m_pQuackBehavior)
{
delete m_pQuackBehavior;
}
m_pQuackBehavior = qb;
}
protected:
FlyBehavior* m_pFlyBehavior;
QuackBehavior* m_pQuackBehavior;
};
class MallardDuck:public Duck
{
public:
MallardDuck()
{
m_pFlyBehavior = new FlyWithWings();
m_pQuackBehavior = new Quack();
}
void display()
{
printf("I'm a real Mallard duck\n");
}
};
int main()
{
Duck* mallard = new MallardDuck();
mallard->performFly();
mallard->perfromQuack();
mallard->setFlyBehavior(new FlyNoWay());
printf("My wings hurt!!\n");
mallard->performFly();
delete mallard;
return 0;
}
运行结果如下:
I'm flying!!
Quack
My wings hurt!!
I can't fly
参考图书:《Head First 设计模式》