Policy (strategy) mode
The strategy pattern in LePUS3 (legend) policy mode, as a software design pattern, refers to an object having a behavior, but in different scenarios, the behavior has different implementation algorithms, such as everyone to "pay personal income tax", but "in the United States to pay personal income tax" and " Income tax in China "there are different methods of tax calculation. The policy pattern makes the algorithm independent of the customers who use it.
The main implementation method is to decouple some functional properties from the target object to form a separate function object, and the target object can combine different functional objects according to the requirement. The following example decouples a duck's flight and quack functions from a duck, using combinations rather than inheritance. The child of a duck can choose to fly and croak the realization class according to the demand when inheriting the duck.
#include <memory>classFlybehaviour;classQuackbehavior;classduck{ Public: Duck (); ~Duck (); Virtual voidDisplay () =0; voidSetflybehaviour (std::shared_ptr<flybehaviour>&behavior); voidSetquackbehavior (std::shared_ptr<quackbehavior>&behavior); voidPerformflybehaviour (); voidPerformquackbehavior ();protected: Std::shared_ptr<FlyBehaviour>M_flybehavior; Std::shared_ptr<QuackBehavior>M_quackbehavior;};
#include"FlyBehaviour.h"#include"QuackBehavior.h"Duck::D uck () {}duck::~Duck () {}voidDuck::setflybehaviour (std::shared_ptr<flybehaviour>&behavior) {M_flybehavior=behavior;}voidDuck::setquackbehavior (std::shared_ptr<quackbehavior>&behavior) {M_quackbehavior=behavior;}voidDuck::p erformflybehaviour () {M_flybehavior-fly ();}voidDuck::p erformquackbehavior () {M_quackbehavior-quack ();}
class flybehaviour{ public : Flybehaviour (); ~flybehaviour (); virtual void fly () = 0 ;};
#include flybehaviour.h " class flywithwings: public Span style= "color: #000000;" > flybehaviour{ public : Flywithwings (); ~flywithwings (); virtual void Fly ();};
flywithwings::flywithwings () {}flywithwings::~flywithwings () {}void flywithwings:: Fly () { "I can fly with wings" << Std::endl;}
" Duck.h " class Public duck{public: Redduck (); ~Redduck (); void display ();};
#include"RedDuck.h"#include<iostream>#include"FlyWithWings.h"#include"Squeak.h"Redduck::redduck () {std::shared_ptr<FlyBehaviour> Flyb (Newflywithwings ()); Std::cout<<"Behavior Counter"<< Flyb.use_count () <<Std::endl; Setflybehaviour (FLYB); Std::cout<<"Behavior Counter"<< Flyb.use_count () <<Std::endl; Std::shared_ptr<QuackBehavior> quackb (NewSqueak ()); Setquackbehavior (QUACKB);} Redduck::~Redduck () {}voidRedduck::d isplay () {std::cout<<"I am a red duck!"<<Std::endl; Performflybehaviour (); Performquackbehavior ();}
?
Policy Mode C + + implementation