C + + 's policy model

Source: Internet
Author: User

1 flying Ducks.

Duck base class, containing two member functions (swim, display), derived classes Mallardduck,redheadduck and Rubberduck, each overriding the display member function inherited from the base class

class Duck {public:    void  swim ();     Virtual void display ();};  Public Duck {public:    void//  Adding virtual is OK and not Necessary}; class Redheadduck ...

Now, what should be done to increase the flying skills of the Ducks-fly?

1.1 Inheritance

Considering that not all ducks can fly, add a normal virtual function fly to the Duck, then the "Fly" derived class inherits a default implementation of fly, and the derived class "does not fly" overrides the implementation of fly

void Duck::fly () {  "I am flying! " << Std::endl;  } void Rubberduck::fly () {  "I cannot fly! " " << Std::endl;  }

1.2 Interface

In fact, the use of general virtual functions to achieve polymorphism is not a strategy, in the first c++11 of the override keyword "1.2 General virtual function" has been explained, the commonly used substitution method is "pure virtual function + default implementation",

The fly is declared as a pure virtual function in the base class, and a default implementation is written

Because it is a pure virtual function, only the "interface" is inherited, and the default "Implementation" is not inherited, whether to invoke the default implementation of fly in the base class, depending on the fly function overridden in the derived class

void
void Redheadduck::fly () {duck::fly ();}

1.3 Design Patterns

So far, the design pattern has not been used, but the problem seems to have been solved, actually using or not using design patterns, depending on the actual needs, also depends on the developer

<design patterns>, the applicable scenarios for the policy model are as follows:

1) Many related classes differ only in their behavior

2) You need different variants of a algorithm

3) An algorithm uses data, clients shouldn ' t know about

4) A class defines many behaviors, and these appear as multiple conditional statements in its operations

Obviously, the various derived classes of ducks belong to "related classes", the key is "fly" This behavior, if only the "fly" behavior, simply divided into "can Fly" and "Do not fly", then do not use design patterns can completely

If "flight mode", with the increase of the derivative class, there will be at least dozens of kinds of, or the "flight mode" as an algorithm, will continue to improve in the future, or "flight mode" as the encapsulation algorithm, provided to third party use.

At this point, the value of the design pattern is reflected-easy to reuse, easy to expand, easy to maintain.

And the 4th kind of application scenario, more in the refactoring-"Replace Type Code with state/strategy"

2 Design Principles

Before you elicit the strategy pattern, look at the three design principles of object oriented

1) Isolation change :identify What varies and separate them from what stays the same

Duck base class, it is obvious that the "flight mode" is a change, so the fly is chosen, and the remaining constant separation

2) programming to Interface: program to a interface, not an implementation

After the fly is separated, it is encapsulated as an interface, which implements a variety of "flight methods" (a series of "Algorithms"), and the addition or modification of the algorithm is carried out in this interface. "Interface" corresponds to C + + is the abstract base class,

The "Flight method" is encapsulated as a Flybehavior class in which the fly member function is declared as pure virtual function

class Flybehavior {public:    virtualvoid0;}; class  Public Flybehavior {public:    virtualvoid  fly ();}; class Flynoway ... class Flywithrocket ...

The implementation of a variety of different algorithms-"flight mode", as follows:

void Flywithwings::fly () {  "I am flying! " << Std::endl;  } void Flynoway::fly () {  "I cannot fly! " " << Std::endl;  } void Flywithrocket::fly () {  "I am flying with a rocket! " << Std::endl;}

3) composite > Inheritance : Favor composition (has-a) over Inheritance (IS-A)

<effective c++> clause 32 mentions that public succession is "is-a", while clause 38 refers to the meaning of composition (composition or composition) as "Has-a". therefore, in the Duck base class, you can

Declares a pointer to the Flybehavior type, so that the corresponding "algorithm"-the "flight mode"-can be invoked simply by _PFB the pointer.

class Duck {public:    ... Private :    Flybehavior* _PFB;  // or std::shared_ptr<flybehavior> _pfb;};

3 Policy mode

3.1 Content

Even if you do not understand the design patterns, only in strict accordance with the above three design principles, the final design ideas will be similar to the strategy model, may be just a few subtle differences

Here's a look at the specifics and structure of the Strategy model:

defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently

From clients it.


The context points to strategy (implemented by pointers); The context invokes a series of algorithms through the strategy interface , and Concretestrategy implements a series of The specific algorithm

3.2 Smart Pointers

In the above example, the "interface" of the policy pattern corresponds to the abstract base class Flybehavior, and the "algorithm implementation" corresponds to the derived class flywithwings, Flynoway, Flywithrocket, and "reference" corresponding to the _PFB pointer

To simplify memory management, you can declare _PFB as a "smart pointer", and in the constructor of the Duck class, initialize the "smart pointer"

Duck::D uck (std::shared_ptr<flybehavior> pflybehavior): _PFB (pflybehavior) {}

Intuitively, Duck corresponds to the Context, but the Duck base class does not invoke various "flight methods"-that is, "algorithms"-directly through the Flybehavior interface, which is actually derived classes Mallardduck,redheadduck and

Rubberduck, in this way, you need to initialize the _PFB in the constructors of each derived class.

Mallardduck::mallardduck (std::shared_ptr<flybehavior> pflybehavior): Duck (pflybehavior) {}

Then, in the Duck base class, the call to fly is implemented by pointer _PFB

void Duck::p erformfly () {    _pfb-fly ();}

In addition to initializing _PFB in the constructor, you can define a Setflybehavior member function in the Duck class, dynamically setting the "Fly Mode"

void Duck::setflybehavior (std::shared_ptr<flybehavior> pflybehavior) {    = pflybehavior;}

Finally, the main function is as follows:

void Main () {    shared_ptr<FlyBehavior> pfwings = make_shared<flywithwings>();     shared_ptr<FlyBehavior> pfrocket = make_shared<flywithrocket>();     // Fly with wings    shared_ptr<duck> Pduck = make_shared<mallardduck>(pfwings);    Pduck, Performfly ();

// fly with a rocket pduck-Setflybehavior (pfrocket); Pduck-Performfly ();}

Summary:

1) object-oriented three design principles: Isolation change, programming to interface, composition > Inheritance

2) The strategy model mainly involves "a series of algorithms", familiar with its four scenarios

Resources:

< Design Patterns > Chapter II

<effective c++> Item, item 38

<design paterns> Strategy

<Refactoring> Chapter 8

C + + 's policy model

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.