Design Pattern-Observer Pattern
In the previous article, we talked about the strategy model. In this article, we will talk about the observer model. The Observer Model is also a widely used design model, such as some tree-structured game engines, the association between the parent node and the child node. The essence of the observer mode is to establish a one-to-many dependency between the target object and the observer object. When the State of the target object changes, the state of the observer object automatically changes.
Observer mode:
The following code is compiled on VS2012
. H file:
# Include
Using namespace std; class Observer // abstract Observer class {public: virtual void update (); // The Observer observes the response after the target changes}; class ConcreteObserver1: public Observer // specific Observer class 1 {public: void update () ;}; class ConcreteObserver2: public Observer // specific Observer class 2 {public: void update ();}; class Target // abstract Target class {protected: list
MObserverList; // use a linked list to record the public: void addObs (Observer *) of the target Observer; // Add a new Observer void deleteObs (); // delete an observer virtual void y (); // notify all other corresponding observers when the current Target changes}; class ConcreteTarget: public Target // The specific Target class {public: void y ();};
. Cpp file:
void Observer::update(){}void ConcreteObserver1::update(){ cout<::iterator i; for(i=mObserverList.begin();i!=mObserverList.end();i++) { (*i)->update(); }}
Call file:
Int _ tmain (int argc, _ TCHAR * argv []) {Observer * ob1 = new ConcreteObserver1 (); // create a specific Observer 1Observer * ob2 = new ConcreteObserver2 (); // create a specific observer 2Target * mt = new ConcreteTarget (); // create a specific target mt-> addObs (ob1 ); // Add the corresponding observer 1mt-> addObs (ob2); // Add the corresponding observer 2mt-> Y (); // the target State changes, notify all observers to return 0 ;}
Execution result:
I am ConcreteObserver1
I am ConcreteObserver2