策略(Strategy)模式
Strategy pattern in LePUS3 (legend) 策略模式作为一种软件设计模式,指对象有某个行为,但是在不同的场景中,该行为有不同的实现算法,比如每个人都要“交个人所得税”,但是“在美国交个人所 得税”和“在中国交个人所得税”就有不同的算税方法。策略模式让算法独立于使用它的客户而独立变化。
其主要实现方法就是将某些某些功能属性从目标对象中解耦出来构成单独的功能对象,目标对象可以根据需求组合不同的功能对象。下面示例将鸭子的飞行和呱呱叫功能从鸭子中解耦出来,使用组合而不是继承来实现。鸭子的子类在继承鸭子的时候可以根据需求自由的选择飞行和呱呱叫的实现类。
#includeclass FlyBehaviour;class QuackBehavior;class Duck{public: Duck(); ~Duck(); virtual void display() = 0; void setFlyBehaviour(std::shared_ptr & behavior); void setQuackBehavior(std::shared_ptr & behavior); void performFlyBehaviour(); void performQuackBehavior();protected: std::shared_ptr m_flyBehavior; std::shared_ptr m_quackBehavior;};
#include "FlyBehaviour.h"#include "QuackBehavior.h"Duck::Duck(){}Duck::~Duck(){}void Duck::setFlyBehaviour(std::shared_ptr& behavior){ m_flyBehavior = behavior;}void Duck::setQuackBehavior(std::shared_ptr & behavior){ m_quackBehavior = behavior;}void Duck::performFlyBehaviour(){ m_flyBehavior->fly();}void Duck::performQuackBehavior(){ m_quackBehavior->quack();}
class FlyBehaviour{public: FlyBehaviour(); ~FlyBehaviour(); virtual void fly() = 0;};
#include "FlyBehaviour.h"class FlyWithWings : public FlyBehaviour{public: FlyWithWings(); ~FlyWithWings(); virtual void fly();};
FlyWithWings::FlyWithWings(){}FlyWithWings::~FlyWithWings(){}void FlyWithWings::fly(){ std::cout << "I can fly with wings" << std::endl;}
#include "Duck.h"class RedDuck : public Duck{public: RedDuck(); ~RedDuck(); void display();};
#include "RedDuck.h"#include#include "FlyWithWings.h"#include "Squeak.h"RedDuck::RedDuck(){ std::shared_ptr flyB(new FlyWithWings()); std::cout << "behavior counter " << flyB.use_count() << std::endl; setFlyBehaviour(flyB); std::cout << "behavior counter " << flyB.use_count() << std::endl; std::shared_ptr quackB(new Squeak()); setQuackBehavior(quackB);}RedDuck::~RedDuck(){}void RedDuck::display(){ std::cout << "I am a red duck!" << std::endl; performFlyBehaviour(); performQuackBehavior();}