C # design model-Observer Pattern-start with the ticket deletion reminder in the company management system

Source: Internet
Author: User

Observer 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.

    • Abstract topic role: The topic role stores all references to the observed objects in one aggregation. Each topic can have any number of observers. An abstract topic provides an interface to add and delete observer objects. A Topic role is also called an abstract observer role. It is generally implemented using an abstract class or an interface.
    • Abstract observer (observer) Role: Defines an interface for all the specific observers and updates themselves when receiving notifications of the topic. This interface is called the update interface. Abstract observer roles are generally implemented using an abstract class or an interface. In this schematic implementation, the update Interface contains only one method (that is, the update () method). This method is called the update method.
    • Concretesubject role: Stores the relevant status to a specific observer object. When the internal status of a specific topic changes, a notification is sent to all registered observers. A topic role is also called a concrete observable ). A topic role is usually implemented by a specific subclass.
    • Concreteobserver role: The storage status is the same as that of the topic. The observer role implements the update interface required by the abstract observer role, so that the state of the observer can be consistent with the state of the topic. If necessary, the observer role can save a reference pointing to a specific topic object. A specific observer role is usually implemented by a specific subclass.

The synthesis relationship between a specific topic role and an abstract observer role indicates that a specific topic object can be referenced by any number of abstract observer objects. The use of abstract observer instead of specific Observer means that the topic object does not need to know which concreteobserver types are referenced, but only the abstract observer type. This allows a specific topic object to dynamically maintain a series of references to the observer object and call the update () method shared by each observer as needed. This is called "abstract programming ". (Refer to Lu Zhenyu's blog)

 

The development of the observer pattern has evolved into several versions. The most classic example is the mouse hole. At this time, the cat started to catch the mouse. This is a single task, and the doll started to cry, this becomes the multi-task of the observer, which is used in his own work. In the company's internal management system, when one department deletes a customer, at the same time, the message is sent to every staff member in other departments. At this time, we can use the multi-task mode in observer mode.

When a single task is executed, we can directly call this task method through object reference. However, when there are multiple tasks, we can choose to use list <Object>. When the object is acted by the observer, by the observer, We can traverse all objects and send notifications. in a simple way, we can use delegate to register objects, and finally notify every observer by triggering events.

First, let's take a lookCode:

View code

 Using  System;  Using  System. Collections. Generic; Using  System. text;  Namespace  Observerpattern {  //  Define the delete ticket abstract interface      Public   Interface  Observable {  Void Delete ( Int  ID );}  //  The Cooperation Department can delete the list. At this time, every object registered to the agent event is notified and the update method is called.      Class Cooperationobservable: observable {  Public   Delegate   Void Idelegate ( Int  ID );  Public   Event  Idelegate adeletage;  Public   Void Delete ( Int  ID) {adeletage (ID );}}  // Observer Interface      Public   Interface  Observer {  Void Update ( Int  ID );}  //  Observer object      Class  Concreateobserver: Observer {  String  Name;  Public   String Name {  Set {Name = Value ;}  Get { Return  Name ;}}  Public Concreateobserver ( String  Aname) {name = Aname ;}  //  Update          Public   Void Update (Int  ID) {console. writeline (name + "  :  " + ID + "  List deleted  "  );}}  Class  Program {  Static   Void Main ( String  [] ARGs ){ //  Three observers Concreateobserver aobserver = New Concreateobserver ( "  Wang Rui  "  ); Concreateobserver bobserver = New Concreateobserver ( "  Wang Lingling  "  ); Concreateobserver cobserver = New Concreateobserver ("  Wei Qing  "  ); Cooperationobservable asubject = New  Cooperationobservable (); asubject. adeletage + = New  Cooperationobservable. idelegate (aobserver. Update); asubject. adeletage + = New  Cooperationobservable. idelegate (bobserver. Update); asubject. adeletage + = New Cooperationobservable. idelegate (cobserver. Update); asubject. Delete (  15  );}}} 

Of course, if we have to use delegate for implementation, there is still much room for optimization in this Code. Because delegate itself implements abstraction, It is programming for interfaces. We can register the methods we need in delegate when we need them.

Let's see if delegate is not applicable:

View code

 Using  System;  Using  System. Collections. Generic;  Using  System. text;  Namespace Observerpattern {  //  Define the delete ticket abstract interface      Public   Interface  Observable {  Void Delete ( Int  ID );}  //  The Cooperation Department can delete the list, implement the registration method, and register the observer to the observer list.      Class  Cooperationobservable: observable {list <Observer> listobserver = New List <observer> ();  Public   Void Delete ( Int  ID ){  Foreach (Observer I In  Listobserver) I. Update (ID );}  Public   Void  Register (Observer aobserver) {listobserver. Add (aobserver );}}  //  Observer Interface     Public   Interface  Observer {  Void Update ( Int  ID );}  //  Observer object      Class  Concreateobserver: Observer {  String  Name;  Public   String  Name { Set {Name = Value ;}  Get { Return  Name ;}}  Public Concreateobserver ( String  Aname) {name = Aname ;}  //  Update          Public   Void Update ( Int ID) {console. writeline (name + "  :  " + ID + "  List deleted  "  );}}  Class  Program {  Static   Void Main ( String  [] ARGs ){  // Three observers Concreateobserver aobserver = New Concreateobserver ( "  Wang Rui  "  ); Concreateobserver bobserver = New Concreateobserver ( "  Wang Lingling  "  ); Concreateobserver cobserver = New Concreateobserver ( " Wei Qing  "  ); Cooperationobservable asubject = New  Cooperationobservable (); asubject. Register (aobserver); asubject. Register (bobserver); asubject. Register (cobserver); asubject. Delete (  15  );}}} 

The observer pattern has many implementation methods, such as the above Code. We can implement the registration method in the observer, and the effect is the same.

Advantages and disadvantages of observer Mode

The advantage of the observer mode is that the presentation layer and the data logic layer are separated, and a stable update message transmission mechanism is defined. The categories are clear and the update interface is abstracted, this makes it possible to have a variety of presentation layers (observer ).

However, the disadvantage is that each appearance object must inherit the interface class derived from this image, which makes it inconvenient. For example, a appearance object written by someone else does not inherit this abstract class, or the interface is incorrect, and we want to directly use it without modifying the class. Although the adapter mode can be applied to solve this problem to a certain extent, it will cause more complicated and cumbersome design and increase the chance of errors.

The observer mode has the following advantages:

(1) The observer mode establishes an abstract coupling between the observer and the observer. What the observer role knows is that a specific observer aggregates, and each specific observer conforms to an abstract observer interface. The observer does not know any specific observer, but only knows that they all have a common interface. Since the observer and observer are not closely coupled, they can belong to different abstract layers.

(2) The observer mode supports broadcast communication. The observer sends a notification to all registered observers.

The observer mode has the following Disadvantages:

(1) It takes a lot of time to notify all observers if they have many direct and indirect observers.

(2) If there is a circular dependency between the observer, the observer will trigger a circular call between them, resulting in system crash. Pay special attention to this when using the observation test mode.

(3) If the notification to the observer is asynchronously delivered through another thread, the system must ensure that the delivery is carried out in an appropriate manner.

(4) Although the observer mode can enable the observer to know the changes of the observed object at any time, the observer mode does not have a mechanism to let the observer know how the observed object changes.

 

Reprinted please indicate the source: edward_jie, http://www.cnblogs.com/promise-7

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.