C # design pattern-Observer Pattern

Source: Internet
Author: User

C # design pattern-Observer Pattern
Preface recently, I began to focus on the design pattern, mainly to make the code written by myself highly reusable and ensure code reliability. The so-called design pattern is defined by me as a summary of code design experiences that have been repeatedly used, known to most people, classified and catalogued. There is no doubt that the design pattern is win-win for others and the system; The design pattern enables code compilation to be truly engineered; The design pattern is the cornerstone of the software engineering, just like the structure of the building. Why do we advocate "Design Pattern )"? The root cause is to reuse code and increase maintainability. So this time we will study the design patterns, and finally use the C # language to implement these design patterns as an example to deeply understand the essence. The observer mode is sometimes called the publish/subscribe mode. The observer mode defines a one-to-many dependency, allowing multiple observer objects to listen to a topic object at the same time. When the status of this topic object changes, it notifies all observer objects so that they can automatically update themselves. Role 1 in feature mode. Abstract topic: It stores reference of all observer objects in one aggregation. Each topic can have any number of observers. Abstract topic provides an interface to add and delete observer objects. 2. ConcreteSubject: stores the status in a specific observer object, and sends a notification to all registered observers when the status of the subject changes. 3. Abstract Observer: defines an interface for all specific observers and updates themselves when receiving topic notifications. 4. ConcreteObserver: implements the update interface required by the abstract observer role to coordinate its status with the topic status. · Advantages and Disadvantages: 1. The notification communication observer mode supports broadcast communication. The observer sends a notification to all registered observers. 2. The clustered observer mode establishes an abstract coupling between the observer and the observer. The observer does not know any specific observer, but stores the list of abstract observers, each specific observer conforms to an abstract observer interface. Disadvantages: 1. time complexity it takes a lot of time to notify the audience of a large number of direct and indirect observers. Ii. inlining deficiency although the observer mode can enable the observer to know that the observed object has sent a change at any time, the observer mode does not have a mechanism to let the observer know how the observed object has changed. 3. It is prone to loop calls. If circular dependencies exist between the observer, the observer will trigger cyclic calls between them, resulting in system crash. Pay special attention to this when using the observer mode. The following is an example of xmfdsh publishing a blog to illustrate the implementation of the observer mode. After paying attention to xmfdsh, you can use the observer mode to get the blog updated information in real time. When an abstract model has two aspects, one of which depends on the other, the two are encapsulated in an independent object so that they can be changed and reused independently. From the word aspect, we can think that the observer mode must be reflected in AOP (Aspect-Oriented Programming. Therefore, this requirement can be solved simply by using the observer model. The observer "subscribes" to the change of the target, and after the change of the target, the observer "notifies" all the "subscribed" changes, and then executes the "subscribed" content. The advantage of this mechanism is to reduce coupling and clarify the division of labor. The goal is only to send "notifications" to the subscription list when its status changes or some behavior is made ", instead of directly calling the observer's behavior (method), the observer is only responsible for "subscribing" its changes to the target, and define the specific behavior (that is, the subscribed content) that must be performed after the target "notification" is received) copy the code // subscribe number abstract class public abstract class Blog {// Save the subscriber List private List <IObserver> observers = new List <IObserver> (); public string Symbol {get; set ;}// information about the subscription number public string Info {get; set ;}// information about this update public Blog (string symbol, string info) {this. symbol = symbol; This. info = info;} // The public void AddObserver (IObserver ob) {observers. add (ob);} public void RemoveObserver (IObserver ob) {observers. remove (ob);} public void Update () {// traverse the subscriber list to notify foreach (IObserver ob in observers) {if (ob! = Null) {ob. receive (this) ;}}}// specific subscription number class public class MyBlog: Blog {public MyBlog (string symbol, string info): base (symbol, info) {}}// Subscriber interface public interface IObserver {void Receive (Blog tenxun);} // specific Subscriber class public class Subscriber: IObserver {public string Name {get; set ;} public Subscriber (string name) {this. name = name;} public void Receive (Blog xmfdsh) {Console. writeLine ("subscription The reader {0} observed {1} {2} ", Name, xmfdsh. symbol, xmfdsh. info) ;}// client test class Program {static void Main (string [] args) {Blog xmfdsh = new MyBlog ("xmfdsh ", "published a new blog"); // Add the subscriber xmfdsh. addObserver (new Subscriber ("Wang Nima"); xmfdsh. addObserver (new Subscriber ("Tang moru"); xmfdsh. addObserver (new Subscriber ("Wang peach"); xmfdsh. addObserver (new Subscriber (" Nima"); // update information xmfdsh. update (); // output the result. At this time, all subscribers have received the blog's New Message Co Nsole. ReadLine () ;}} this class chart is generated by visual studio and may seem confusing. This implementation is the implementation of the observer mode. At any time, if the Update method is executed, it will automatically notify the user who has subscribed to this subscription number. However, in C, we use delegation and events to simplify the implementation of the observer mode. Copy the code class Program {// delegate to act as the subscriber interface class public delegate void policyeventhandler (object sender); // abstract the subscriber class public class Blog {public policyeventhandler policyevent; public string Symbol {get; set ;}// information about the subscription number public string Info {get; set ;}// information about this update public Blog (string symbol, string info) {this. symbol = symbol; this. info = info ;}# region adds public void AddObserver (NotifyEventHandl Er ob) {policyevent + = ob;} public void RemoveObserver (policyeventhandler ob) {policyevent-= ob;} # endregion public void Update () {if (policyevent! = Null) {policyevent (this) ;}}// specific subscription number class public class MyBlog: Blog {public MyBlog (string symbol, string info): base (symbol, info) {}}// Subscriber class public class Subscriber {public string Name {get; set;} public Subscriber (string name) {this. name = name;} public void Receive (Object obj) {Blog xmfdsh = obj as Blog; if (xmfdsh! = Null) {Console. writeLine ("subscriber {0} observed {1} {2}", Name, xmfdsh. symbol, xmfdsh. info) ;}} static void Main1 (string [] args) {Blog xmfdsh = new MyBlog ("xmfdsh", "published a new Blog "); subscriber wnm = new Subscriber ("Wang Nima"); Subscriber tmr = new Subscriber ("Tang Maru"); Subscriber wmt = new Subscriber ("Wang peach "); subscriber anm = new Subscriber (" Nima"); // Add the Subscriber xmfdsh. addObserver (new NotifyEventHandler (wnm. receive); xmfdsh. addObserver (new NotifyEventHandler (tmr. receive); xmfdsh. addObserver (new NotifyEventHandler (wmt. receive); xmfdsh. addObserver (new NotifyEventHandler (anm. receive); xmfdsh. update (); Console. writeLine (); Console. writeLine (); Console. writeLine (); Console. writeLine (); Console. writeLine ("Remove subscriber Wang Nima"); xmfdsh. removeObserver (new NotifyEventHandler (wnm. receive); xmfdsh. update (); Console. readLine ();}}

Related Article

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.