Tag: construct color is the initial OWA art PTR protect win
The policy pattern defines the family of algorithms, which are encapsulated separately so that they can be replaced with each other, and this pattern makes the algorithm independent of the object of the algorithm.
The example in the book is the duck, the example of the reference blog is the cache algorithm. Reference blog See: 6665197
Duck:
classFlybehavior { Public: Virtual voidfly () {};};classFlywithwings: PublicFlybehavior { Public: voidFly () {std::cout<<"Fly with Wings"<<Std::endl; }};classFlynoway: PublicFlybehavior { Public: voidFly () {std::cout<<"cannot Fly"<<Std::endl; }};classQuackbehavior { Public: Virtual voidquack () {};};classQuack: PublicQuackbehavior { Public: voidQuack () {std::cout<<"Quack"<<Std::endl; }};classSqueak: PublicQuackbehavior { Public: voidQuack () {std::cout<<"Squeak"<<Std::endl; }};classMutequack: PublicQuackbehavior { Public: voidQuack () {std::cout<<"Mute"<<Std::endl; }};classDuck { Public: Duck (): Flybehavior (nullptr), Quackbehavior (nullptr) {}; voidFly () {Flybehavior-Fly (); } voidQuack () {Quackbehavior-Quack (); }protected: Flybehavior*Flybehavior; Quackbehavior*Quackbehavior;};classMallardduck: Publicduck{ Public: Mallardduck () {Flybehavior=Newflywithwings; Quackbehavior=NewQuack; } ~Mallardduck () {DeleteFlybehavior; DeleteQuackbehavior; }};
The differences compared to Java are mainly:
1. For the parent type of the encapsulated algorithm, it is defined as a pointer when it is a member of a class.
2. This is not much of a relationship with Java. When a class member variable has pointers, it needs to implement its own destructor.
The difference between the implementation of the algorithm and the reference blog is:
1. Referring to the algorithm of the blog, the constructor needs to pass in a parameter indicating the type and algorithm implementation. Ducks in this example, different ducks integrate the Duck parent class, and then initialize the parent class member pointer in the subclass constructor.
Design mode C + + (2)--Policy mode