Objective
Recently began to spend a bit of thought research design patterns, mainly to let themselves write code reusability, and ensure the reliability of the code. The so-called design pattern, I looked for the following definition: is a set of repeated use, most people know, after the classification purposes, code design experience Summary. There is no doubt that design patterns in others in the system are multi-win; Design patterns make code production truly engineering; Design patterns are the cornerstone of software engineering, like the structure of a building.
Why should you advocate design pattern?
The root cause is for code reuse, which increases maintainability. So this time we will learn the design patterns, and finally through the C # language to implement these design patterns as an example, a deep understanding of the essence.
definition
The observer pattern, sometimes referred to as the Publish/subscribe pattern, defines a one-to-many dependency that allows multiple observer objects to listen to a Subject object at the same time. This subject object notifies all observer objects when the state changes, enabling them to automatically update themselves.
Characteristics
Roles that are in a pattern
1. Abstract Theme (Subject): It saves references to all observer objects in a single aggregation, and each subject can have any number of observers. Abstract topics provide an interface that allows you to add and remove observer objects.
2. Specific topic (ConcreteSubject): The status of the State is deposited into the specific observer object, and all registered observers are notified when changes are made to the internal state of the specific subject.
3. Abstract Observer (Observer): Defines an interface for all specific observers to update themselves when subject notifications are received.
4. Specific observer (Concreteobserver): Implements the update interface required by the abstract observer role in order to reconcile its state with the subject state.
·
Pros and cons
Advantages:
I. Notification of communication
The Observer pattern supports broadcast communication. The observed person notifies all registered observers.
Two, poly-coupling
The Observer pattern creates an abstract coupling between the observer and the Observer, and the observer does not know of any specific observer, but simply holds the list of abstract observers, each of which conforms to the interface of an abstract observer.
Disadvantages:
One, the complexity of time
If an observer object has many direct and indirect observers, all observers are informed that it will take a lot of time.
Ii. inadequacy of the internal union
Although the observer pattern can always make the observer aware that the object being observed sends a change, the observer pattern does not have a mechanism for the observer to know how the observed object has changed.
Third, easy to appear circular call
If there is a cyclic dependency between the observers, the observed will trigger a cyclic call between them, causing the system to crash, which should be particularly noted in using the Observer pattern.
Implementation Ideas
The following is an example of a blog post with Xmfdsh to illustrate the implementation of the Observer pattern. With the attention of XMFDSH's friends, we can get the updated information in real-time through the Observer mode. When an abstract model has two facets, one of which relies on another, encapsulating the two in separate objects so that they can be individually changed and reused. From the word, it can be thought that the observer pattern is definitely embodied in AOP (aspect-oriented programming). So the need to use the observer pattern to solve it is more appropriate.
The Observer "subscribes" to the target for its change, and "notifies" all observers who have "subscribed" to its change after the target has changed, thus executing the content of the "subscription". The advantage of this mechanism is to reduce the coupling, the division of labor is clear, the goal is only responsible for the changes in their own state or to make a certain behavior when the "notification" of their own subscription list, rather than directly invoke the observer's behavior (method); The specific behavior you need to make (that is, the content of the subscription)
//Subscription Number abstract class Public Abstract classBlog {//Save Subscribers List PrivateList<iobserver> observers =NewList<iobserver>(); Public stringSymbol {Get;Set; }//descriptive information about the subscription number Public stringInfo {Get;Set; }//The information describing this update PublicBlog (stringSymbolstringinfo) { This. Symbol =symbol; This. Info =info; } //Add and remove subscribers to the same subscription number Public voidaddobserver (IObserver ob) {observers. ADD (OB); } Public voidremoveobserver (IObserver ob) {observers. Remove (OB); } Public voidUpdate () {//traverse the subscriber list for notification foreach(IObserver obinchobservers) { if(Ob! =NULL) {ob. Receive ( This); } } } } //specific subscription number class Public classMyblog:blog { PublicMyBlog (stringSymbolstringinfo):Base(symbol, info) {}}//subscribers ' interfaces Public InterfaceIObserver {voidReceive (Blog Tenxun); } //the specific subscriber class Public classSubscriber:iobserver { Public stringName {Get;Set; } PublicSubscriber (stringname) { This. Name =name; } Public voidReceive (Blog xmfdsh) {Console.WriteLine ("the subscriber {0} observed {1}{2}", Name, xmfdsh. Symbol, Xmfdsh. Info); } } //Client Testing classProgram {Static voidMain (string[] args) {Blog xmfdsh=NewMyBlog ("xmfdsh","posted a new blog"); //Add SubscribersXmfdsh. Addobserver (NewSubscriber ("Wang Nima")); Xmfdsh. Addobserver (NewSubscriber ("Tangmaru")); Xmfdsh. Addobserver (NewSubscriber ("Peach King")); Xmfdsh. Addobserver (NewSubscriber ("Onima")); //Update Informationxmfdsh. Update (); //output, at which point all subscribers have been given new messages from the blogConsole.ReadLine (); } }
Run the following
The class diagram for this implementation method is as follows:
This class diagram is generated by Visual Studio and may seem confusing, and this implementation is the implementation of the Observer pattern. Whenever the Update method is executed, the notification is automatically pushed to the subscriber subscribing to the subscription number, whereas in C # we use delegates and events to simplify the implementation of the Observer pattern.
classProgram {//Delegates act as subscriber interface classes Public Delegate voidNotifyeventhandler (Objectsender); //Abstract Subscription Number class Public classBlog { PublicNotifyeventhandler notifyevent; Public stringSymbol {Get;Set; }//descriptive information about the subscription number Public stringInfo {Get;Set; }//The information describing this update PublicBlog (stringSymbolstringinfo) { This. Symbol =symbol; This. Info =info; } #regionNew maintenance operation for list of subscription numbers Public voidaddobserver (Notifyeventhandler ob) {notifyevent+=ob; } Public voidremoveobserver (Notifyeventhandler ob) {notifyevent-=ob; } #endregion Public voidUpdate () {if(Notifyevent! =NULL) {notifyevent ( This); } } } //specific subscription number class Public classMyblog:blog { PublicMyBlog (stringSymbolstringinfo):Base(symbol, info) {}}//specific Subscriber class Public classSubscriber { Public stringName {Get;Set; } PublicSubscriber (stringname) { This. Name =name; } Public voidReceive (Object obj) {Blog xmfdsh= obj asBlog; if(Xmfdsh! =NULL) {Console.WriteLine ("the subscriber {0} observed {1}{2}", Name, xmfdsh. Symbol, Xmfdsh. Info); } } } Static voidMain1 (string[] args) {Blog xmfdsh=NewMyBlog ("xmfdsh","posted a new blog"); Subscriber WNM=NewSubscriber ("Wang Nima"); Subscriber TMR=NewSubscriber ("Tangmaru"); Subscriber WMT=NewSubscriber ("Peach King"); Subscriber ANM=NewSubscriber ("Onima"); //Add SubscribersXmfdsh. Addobserver (NewNotifyeventhandler (wnm. Receive)); Xmfdsh. Addobserver (NewNotifyeventhandler (TMR). Receive)); Xmfdsh. Addobserver (NewNotifyeventhandler (WMT. Receive)); Xmfdsh. Addobserver (NewNotifyeventhandler (ANM. Receive)); Xmfdsh. Update (); Console.WriteLine (); Console.WriteLine (); Console.WriteLine (); Console.WriteLine (); Console.WriteLine ("Remove subscribers Wang Nima"); Xmfdsh. Removeobserver (NewNotifyeventhandler (wnm. Receive)); Xmfdsh. Update (); Console.ReadLine (); } }
Results of the operation:
Class Diagram:
Summary
Here, the Observer pattern is done, and the observer pattern defines a one-to-many dependency that allows multiple observer objects to listen to a Subject object at the same time, which notifies all observer objects when a state changes, so that they can automatically update themselves, Therefore, in some requirements is when an object changes need to change multiple other objects at the same time, and do not know how many objects need to notify the change, the observer pattern is the preferred, this pattern is the most used, in my development experience is the Windows Phone Mobile client development, Often use this kind of entrusted event processing, with more after the discovery is accustomed to, this mode is not so unusual.
Source: Http://files.cnblogs.com/xmfdsh/ConsoleApplication2.zip
C # Design Pattern-Viewer mode