The design pattern I understand (C + + implementation)--observer mode (Observer pattern) __c++

Source: Internet
Author: User
Overview:

China's stock market has recently fluctuated, of course, the ups and downs on the business opportunities, Xiaoming found the consequences of the market, bought the Chinese securities, he wanted to be on the computer client, on the web, on the phone, the ipad can be viewed on the real-time market, this case how we should design our software. We can do this: all clients of xiaoming subscribe to the stock of China securities, as long as the stock changes, all clients will be notified and automatically updated.

This is our observer model, which defines a one-to-many dependency between objects, and when an object's state changes, all objects that depend on it are notified and automatically updated.

class Diagrams and instances:

As you can see, there are the following roles in the implementation of this observer pattern:

Abstract Theme (Subject role : The theme role holds all references to the object of observation in one aggregation, and each subject can have any number of observers. Abstract topics provide an interface to add and remove observer objects, which are also called Abstract Observer (observable) roles, typically implemented with an abstract class or an interface.

Abstract Observer (Observer role : Defines an interface for all specific observers and updates itself when a topic is notified. This interface is called the update interface. Abstract observer roles are typically implemented with an abstract class or an interface. In this schematic implementation, the update interface contains only one method (the update () method), which is called the Update method.

Specific topics (ConcreteSubject ) Role : The state is deposited in the specific observer object, and all registered observers are notified when the internal state of the specific subject changes. The specific subject role is also called the specific observer role (concrete observable). Specific theme roles are usually implemented with a specific subclass.

specific Observer (Concreteobserver role : The state of the store and the topic itself. The specific reviewer role implements the update interface required by the abstract observer role to reconcile its own state with the state of the subject. If necessary, the specific reviewer role can save a reference to a specific subject object. The specific observer role is usually implemented with a specific subclass.

From the specific theme role to the abstract observer role of the composite relationship, on behalf of the specific Subject object can have any number of abstract observer object references. The use of abstract observers rather than specific observers means that subject objects do not need to know which concreteobserver types are referenced, but only abstract observer types. This makes it possible for a specific subject object to dynamically maintain a series of references to the observer object and to invoke the update () method shared by each observer when needed. This approach is called "for abstract programming".

Here we offer an example of simplicity:

#include <iostream> #include <vector> #include <string> using namespace std;
Class secretary;
		Look at the stock's colleague class (observed object, observer) classes Stockobserver {public:stockobserver (string strName, secretary* strsub) {name = StrName;
	Sub = strsub;

} void Update ();
	Private:string name;
secretary* Sub;

};
	Secretary class (Subject object, notifying person) class Secretary {public:string action;
	void Add (Stockobserver ob) {observers.push_back (OB);} void Remove (int addindex) {if (Addindex >=0 && Addindex < Observers.size ()) Observers.erase (observers.b
	Egin () + Addindex);
		} void Notify () {Vector<stockobserver>::iterator it; For (It=observers.begin (); It!=observers.end (); ++it) {(*it).
		Update ();
}} private:vector<stockobserver> observers;




}; void Stockobserver::update () {cout << name << ": << sub->action <<", begin to work <& Lt
Endl

	int main () {//create notification secretary* p = new Secretary (); Observer stockobserver* S1 = new Stockobserver ("Lazy", p);

	stockobserver* s2 = new Stockobserver ("SnowFire", p);
	Join the notification queue P->add (*S1);

	P->add (*S2);

	Event P->action = "The Boss is coming ...";

	Notify P->notify ();
	
	Dynamic deletion of p->remove (0);

	P->notify ();

return 0;
 }

Applicability:

1. When an abstract model has two aspects, one aspect relies on the other. Encapsulate the two in separate objects so that they can be changed and reused independently of each other.

2. When a change to an object needs to change other objects at the same time, do not know how many objects to be changed.

3. When an object must notify other objects, it cannot assume that the other object is. In other words, you don't want these objects to be tightly coupled.

pros and Cons:

The effect of the observer pattern has the following advantages:

1. The Observer pattern creates an abstract coupling between the observer and the Observer. What the Observer's role knows is that a specific observer is gathered, each of whom conforms to the interface of an abstract viewer. The observer does not know any specific observer, it only knows that they all have a common interface. Because the observer and the observer are not tightly coupled, they can belong to different levels of abstraction.

2. Observer mode supports broadcast traffic. The observer will give notice to all the registered observers.

The observer pattern has some of the following drawbacks:

1. If an observer has many direct and indirect observers, it will take a lot of time to notify all observers.

2. If there is a circular dependency between the observed, the observer triggers a circular call between them, causing the system to crash. Pay special attention to this when using the observation mode.

3. If the observer's notification is delivered asynchronously through another thread, the system must ensure that the delivery is done in a proper manner.

4. Although the observer model can readily enable the observer to know that the observed object has changed, the Observer pattern does not have a mechanism in place to enable the observer to know how the object of observation has changed.


Other: 1. In. NET, you can use the delegate and event mechanisms to implement the observer pattern. 2.JAVA provides observer and observable to help us simplify the implementation of the Observer pattern.


lcl_data Original in Csdn.net "http://blog.csdn.net/lcl_data/article/details/9208561"

Other Design Patterns refer to: The design pattern I understand

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.