Component collaboration mode in C + + design mode: Template Method, Strategy, Observer

Source: Internet
Author: User

"Component Collaboration" mode:

#现代软件专业分工之后的第一个结果是 "Framework-to-application partitioning", the "component collaboration" mode, which uses late binding to achieve loose coupling between the framework and the application, is a common pattern in collaboration between the two.

#典型模式: Template Method, Strategy, observer/event

Part 1 Template Method template mode

  Motive (motivation)
#在软件构建过程中, for a task, it often has a stable overall operating structure, but the individual sub-steps have many changes in demand, or because of inherent reasons (such as the relationship between the framework and the application) and the overall structure of the task can not be implemented simultaneously.
#如何在确定稳定操作结构的前提下 to flexibly respond to changes in individual sub-steps or to late implementation requirements?

structured Software Design process

  

  Object-oriented Software design process

  

  Early binding and late binding

  

Late binding mechanism implementation method: virtual function, function pointer (c, the most common, C + + virtual function of the underlying principle is also a function pointer).

  Schema definition (Template method)

Defines the skeleton (stability) of an algorithm in an operation, while delaying (changing) some steps into a subclass. The Template method allows subclasses to redefine (override overrides) some specific steps of the algorithm without altering the structure of an algorithm (re-use). --"Design pattern" GoF

  Structure (UML diagram)

  

  Code implementation

The stable code is written as a non-virtual function, and the changed code is written as a virtual function.

The library code is relatively stable, compared to the ABRASTRACTCLSS. The code examples are as follows:

Class Library {public:    void Run () {step1 (); Step2 (); Step3 ();}    ~Library () {};p rotected:    void Step1 () {cout << "Step1" << Endl;};//stable demand    void Step3 () {C Out << "Step3" << Endl; }; Stable demand for    virtual void Step2 () = 0;//changing demand};    

Among them, the Step2 () function is a few unstable requirements, the Library can not pre-determined the future needs, so the subclass to achieve-defined as pure virtual function.

Application is the code that is written to respond to new changes based on new requirements. The code examples are as follows:

Class Application:public library{protected:    virtual void Step2 () {cout << ' application::step2 ' <& Lt Endl }; Sub-class rewrite according to different needs}; 

The Step2 () function is written in the pure virtual function according to the new requirement, and the program is executed at run time.

The client program is called as follows:

int Main () {    library* PLib = new application ();    Plib->Run ();    Delete PLib;    return 0;}    

  Q&a

Q1: Why is the fictional method of a base class A virtual function?

A1: Because subclasses are implemented as pointers (father* p = new Son ()) constructs and calls. So when a subclass is refactored, the destructor of the subclass is called--the virtual destructor of the parent class, the imaginary function overload (override) of the quilt class. Conversely--if the destructor of the parent class is not defined as a virtual function--a pointer implemented with the father* type, when the destructor of its object is only called its own--father class-The imaginary function, which causes the memory leak of the subclass.

Q2: Why is the implementation details of the Library class--step1 (), Step3 () function--defined as protected?

A2: Because these two methods--step1 (), Step3 () function--have nothing to do with the outside world, mainly related to this class and subclass.

  Summary of Points

#Template method mode is a very basic design pattern, which has a large number of applications in object-oriented system. It uses the most concise mechanism (the polymorphism of virtual function) to provide flexible extensibility points for many application frameworks, and is the basic implementation structure of code reuse.

#除了可以灵活应对子步骤的变化外, "Do Not call me, let me call you" the reverse control structure is a typical application of template method.

#在具体实现方面, virtual methods called by template method can have implementations or no implementations (abstract methods, pure virtual methods), but they are generally recommended to be set to the protected method.

#绝大多数软件框架中都有 Template Method mode.

#设计模式必须基于一个稳定点, if there is no applicable design pattern for all instability, the design pattern is not required if all stability is present.

#Template Method means "boilerplate". The run () method is the template, and the details are defined as pure virtual functions, which are defined by the subclass (user).

Part 2 policy mode strategy

  Motive (motivation)

#在软件构建过程中, the algorithms used by some objects can vary and often change, and if they are encoded into an object, the object becomes unusually complex, and sometimes supporting unused algorithms is a performance burden.

#如何在运行时根据需要透明地更改对象的算法? Decoupling the algorithm from the object itself to avoid these problems?

  Pattern definition

Define a series of algorithms, encapsulate them one by one, and make them interchangeable (change) with each other. This pattern allows the algorithm to change (expand, subclass) independently of the client program that uses it (stable). --"Design pattern" GoF

  Uml

  

  Code implementation

To implement a class that calculates the tax rate. Since China, the United States, and future tax rates may be different among countries, a design pattern should be adopted to resist change (changes in business requirements). Starting from the outer layer, a class is confessed to a class, until the inner core of the class.

1. Context class, used to store "contexts" to be used when calculating tax rates.

struct Context {     //In order to simplify the code, the context at which the tax rate is calculated is temporarily undefined};

2. Taxstrategy class, the upper level abstraction for implementing a specific tax rate algorithm. The purpose of the pure virtual function defined is to implement run-time polymorphism.

struct taxstrategy {    virtual double calculate (const context& c) = 0;    Virtual ~taxstrategy (); The destructor method of abstract base class must be defined as virtual function}; 

3. Chinatax class, the implementation class of the specific tax rate algorithm.

struct Chinatax:public taxstrategy{    virtual double calculate (const context& c) {        return 1.0  ;    }};

4. Strategyfactory uses the factory method model to practice the dynamic creation of specific abstract classes. For example, you can generate Chinatax classes, America class objects, and so on.

struct strategyfactory{    taxstrategy* newstrategyfactory () {}}; 

5. SalesOrder class, called by the client-based on my understanding of "big talk design mode".

struct SalesOrder {    taxstrategy *strategy;    SalesOrder (strategyfactory& sf) {        this->strategy = sf.newstrategyfactory ();    }    ~salesorder () {delete this->strategy;};    Double Calculatetax () {Context c; double val = Strategy->calculate (c);//Polymorphic call }};    

  Change

Assuming that one day demand increases and needs to increase business to the US (America), the tax rate algorithm needs to increase support for the United States. With the policy mode, just let the new class inherit the abstract base class Taxstrategy, overriding the virtual function calculate () can!

Expand US business//customer demand change struct Americatax:public taxstrategy {    virtual double calculate (const context& c) { C3/>return 2.0;    }};  

  Summary of Points

#所谓设计模式和面向对象所讲的Reuse: A compilation unit, a binary-level reuse. When the code is finished, compiled, tested, deployed intact, the change in demand is more stable called multiplexing; source-level copy-and-paste is not called reuse.

#Strategy及其子类为组件提供了一系列可重用的算法, which makes it easy for the type to switch between the algorithms as needed at run time.

#Strategy模式提供了用条件判断语句以外的另一种选择, the elimination of conditional judgment statements is the decoupling. Code that contains many conditional judgment statements usually requires strategy mode.

#如果Strategy对象没有实例变量, each context can share the same strategy object, saving object overhead.

Part 3 Watcher Mode Observer

  Motive (motivation)

In the process of software building, we need to establish a "notification dependency" for some objects--the state of an object (the target object) is changed, and all dependent objects (The Observer object) will be notified. If such dependencies are too tight, the software will not be able to withstand changes very well.

Using object-oriented technology, you can weaken this dependency and form a stable dependency. So as to realize the loose coupling of software architecture.

  Application

Resolves the original code destruction dependency inversion Principle (DIP)--Typically, dependencies are compile-time dependent.

Interface (Interface) is the abstract base class in C + +.

The observer pattern is called Listener in Java, and in C # is called an Event.

  Code Show one : from the "Big Talk design mode"

1. Abstract, Stable type: Subject, Observer. The code is as follows:

classObserver { Public:    Virtual voidUpdate () =0;};classSubject { Public:    voidAttach (observer*observer)    {_OBSERVERS.PUSH_BACK (Observer); }    voidDetach (observer*observer)    {_OBSERVERS.REMOVE (Observer); }    voidNotify () { for(Auto &e: _observers) e-update (); }Private: List<Observer*>_observers;};

2. Specific, changing types: ConcreteSubject, Concreteobserver. The code is as follows:

classConcreteSubject: PublicSubject { Public:    voidSetState (stringState ) {_state=State ; }    stringgetState () {return_state; }Private:    string_state;};classConcreteobserver: PublicObserver { Public: Concreteobserver (ConcreteSubject*subject) {_subject=subject; }    Virtual voidUpdate () {_state= _subject->getState (); cout<< _state <<Endl; }Private:    string_state; ConcreteSubject*_subject;};

3. The user invokes the sample code as follows:

int Main () {    ConcreteSubjectnew  ConcreteSubject ();    S->attach (new  concreteobserver (s));    S->setstate ("online! " );    S-notify ();     return 0 ;}

  code show two : from "GoF 23"

1. Stable, abstract "upper class" Category: Subject, Observer. The code is as follows:

structSubject;//claim type, otherwise the Observer call will errorstructObserver {Virtual voidUpdate (subject* sub) =0; Virtual~Observer () {};};structSubject {List<Observer*>_observers; voidAttach (observer*observer)    {_OBSERVERS.PUSH_BACK (Observer); }    voidDetach (observer*observer)    {_OBSERVERS.REMOVE (Observer); }    voidNotify () { for(Auto &e: _observers) e->update ( This); }    Virtual~Subject () {};};

2. Changing, specific classes: ConcreteSubject, Concreteobserver. The code is as follows:

structConcreteSubject: PublicSubject {string_subjectstate; stringgetState () {return_subjectstate; }};structConcreteobserver: PublicObserver {string_observerstate; ConcreteSubject*_subject; Concreteobserver (ConcreteSubject*concreteSubject) {_subject=ConcreteSubject; _subject->attach ( This); }    Virtual voidUpdate (subject*sub) {_observerstate= _subject->getState (); cout<< _observerstate <<Endl; }    Virtual~Concreteobserver () {_subject->detach ( This); }};

3. The user invokes the pattern code example:

int Main () {    ConcreteSubjectnew  ConcreteSubject;    ConcreteobserverNew  Concreteobserver (boss);    Boss"come back! " ;    Boss-Notify ();     return 0 ;}

Pattern Definition

Defines a one-to-many (varying) dependency between objects so that when the state of an object (Subject) changes, all objects that depend on it are notified and updated automatically. --"Design pattern" GoF

  Uml

  Summary of Points

#使用面向对象的抽象, the Observer pattern allows us to independently change the target and the observer, thus Da Josong coupling the dependencies between them.

#目标发送通知时, there is no need to specify an observer, and notifications (which can carry notification information as parameters) are propagated automatically.

#观察者自己决定是否需要订阅通知, the target object is ignorant of this.

#Observer模式是基于事件的UI框架中非常常用的设计模式 is also an important part of the MVC pattern.

Component collaboration mode in C + + design mode: Template Method, Strategy, Observer

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.