Observer patterns for [Geekband] Design Patterns Learning Notes

Source: Internet
Author: User

This article references:: Geekband classroom content, Instructor: Li Jianzhong

: Network information: http://blog.csdn.net/hguisu/article/details/7556625

This article only as own study note, does not represent the authority, because is the beginner, has the mistake to please everybody correct, thanks.

1, what is the Observer mode, where are the application sites?

The Observer pattern (sometimes called the publish-subscribe subscribe> mode, model-view view> mode, source-listener listener> mode, or slave mode) is one of the software design patterns. In this mode, a target object manages all the observer objects that are dependent on it and proactively notifies when its own state changes. This is usually done by calling the methods provided by each observer. This pattern is often used to implement an event-handling system.

--------Section 36,000 definitions

2. Structure

3, through the Code analysis, the composition of the model

As shown: The Observer pattern contains the following roles:

Goal (Subject): The target knows its observer. There can be any number of observers observing the same target. Provides an interface for registering and deleting observer objects.

//goal: The target knows its observer. There can be any number of observers observing the same target. Provides an interface for registering and deleting observer objects. Class form{ Public:    Virtual voidAttach (filespliter* observer);//Registered Observer    Virtual voidDetach (filespliter* observer);//releasing the Observer    Virtual voidNotify ();//notify all registered observers    InterfaceSplobserver {Virtual voidUpdate (Form *) =0;//The Observer updates the status    };}

Target (ConcreteSubject): The status is deposited into each Concreteobserver object.

//Target (mainform): deposit the relevant status to each MainForm objectclassMainForm: Publicform{ Public:    /** * RELEASE the Observer*/    Virtual voidAttach (filespliter*observer) {_observers-Append (Observer); }    /** * Registered Observer*/    Virtual voidDetach (filespliter* observer)//{_observers-REMOVE (Observer);    }; /** * Notify all observers*/    Virtual voidNotify () { forObsinch_observers//Traverse        {            if(observers->getstate () = = This-State ) {Obs->update ( This);    }        }    }; //Set Status    voidButton1_Click (BOOLState ) {         This->state = State;//State ChangeNotify (); }protected: MainForm () {}Private: Testbox*Txtfilepath; TextBox*Txtfilenumber; ProgressBar*ProgressBar; List<FileSpliter*> *_observers;};

Observer (Observer): Defines an update interface for objects that need to be notified when a target is changed. Notifies its individual observers when its state has changed.

/** * Abstract Viewer **/classfilesplitter{ Public:    Virtual voidSplit () =0; Virtual voidUpdate (mainform*) =0; Virtual~Filesplitter () {}protected:    Virtual voidOnProgress (floatvalue) {List<filespliter*>::iterator Itor =_observers.begin ();  while(Itor! =_observers.end ()) (*itor)->displayprogress (value);//Update progress baritor++; }    voidDisplayprogress (intvalue) {ProgressBar-SetValue (value); }}Private:    stringFilePath; intfilenumber; BOOLState ;};


Specific observer (CONCRETEOBSERVER): maintains a reference to the ConcreteSubject object. Stores the state, which should be consistent with the state of the target. Implements the Observer update interface to align its state with the state of the target.

//specific observers 1classSpliter1: Publicfilesplitter{ Public: Spliter1 (mainform*MF) {_subject=MF; _subject->state =true; _subject->attach ( This); }    Virtual~Spliter1 () {_subject->state =false_subject->detach ( This); }    Virtual voidUpdate (MainForm *MF) {_subject->state =true; if(MF = =_subject)    {Split ()}} Virtual voidSplit () {//1. Open File filepath//2. Split the file into filenumber files//3, displayprogress overload, update the progress in 1 way (such as progress bar)displayprogress (value); }Private:    BOOLState ; MainForm*_subject;};//specific observers 2classSpliter2: Publicfilesplitter{ Public: Spliter2 (mainform*MF) {_subject=MF; _subject->state =true; _subject->attach ( This); }    Virtual~Spliter2 () {_subject->state =false; _subject->detach ( This); }    Virtual voidUpdate (MainForm *MF) {_subject->state =true; if(MF = =_subject)    {Split ()}} Virtual voidSplit () {//1. Open File filepath//2. Split the file into filenumber files//3, displayprogress overload, update the progress in 2 ways (such as console ...) )displayprogress (value);Private: MainForm*_subject; BOOLState ;};//specific observers 3classSpliter3: Publicfilesplitter{ Public: Spliter3 (mainform*MF) {_subject=MF; _subject->state =true; _subject->attach ( This); }    Virtual~Spliter3 () {_subject->state =false; _subject->detach ( This); }    Virtual voidUpdate (MainForm *MF) {_subject->state =true; if(MF = =_subject)    {Split ()}} Virtual voidSplit () {//1. Open File filepath//2. Split the file into filenumber files//3, displayprogress overload, update the progress in 3 ways (such as percentage)displayprogress (value); }Private: MainForm*_subject; BOOLState ;};

Main function

NT Main () {    mainformnew  mainform ();    Spliter1New  Spliter1 (MF);    Spliter2New  Spliter2 (MF);    Spliter3New  Spliter3 (MF);     return 0 ;}

4. Summary

1, through the Observer mode, a pair of multi-object notification between the dependency relationship becomes more loose, greatly improved the maintainability and extensibility of the program, but also very well in line with the open-closed principle.

2, the Observer pattern conforms to the opening and shutting principle, the open and closed principle refers to a software entity should be opened to the extension, the modification closes. This means that the software entity must be expanded without being modified. The intent of the template method pattern is to control the top-level logic by the abstract parent class, and defer the implementation of the basic operation to the subclass, which is to achieve the reuse of the object by means of inheritance.

3.

Template method pattern and object encapsulation, object-oriented three major features: inheritance, encapsulation, polymorphism.
The object has internal and external behavior. Encapsulation is for information hiding, and is encapsulated to maintain the integrity of the object's internal data. Allows an external object to not directly access an object's internal state, but must be accessible through the appropriate method. In C + +, the object properties and methods are given the specified modifier (public, protected, private) to achieve the purpose of encapsulation, so that the data is not malicious access to the external object and the method is not incorrectly invoked to cause the encapsulation of the corrupted object.

Observer patterns for [Geekband] Design Patterns Learning Notes

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.