Design Pattern 2: Observer Pattern)

Source: Internet
Author: User

Let's take a look at the definition of the observer mode:

The Observer Pattern defines a one-to-define denpendency between objects so that when one object changes state, all of its dependents are notified and updated automatically.: The Observer mode defines one-to-multiple dependencies between objects. When an object changes its state, all objects dependent on it will be notified and automatically updated.

The observer mode is also called the Publish-Subscribe mode, the Model-View mode, and the Source-Listener mode.

The observer mode defines a one-to-many relationship, allowing multiple observers 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.

One of the more intuitive ways to implement the observer mode is to register-Notification-cancel registration.

First, the Observer registers itself to the Observer object (Subject), and the observed object stores the Observer in a Container.

Second, the observed object has changed. It obtains all registered observers from the container and notifies the observer of the changes.

Finally, the observer tells the observer to cancel the observation and remove the observer from the container.

When an observer registers himself to the container of the observer, the observer should not ask the specific type of the observer, but use the observer interface. The advantage of doing so is that if there are other observers in the program, as long as the observer is the same interface implementation. One observer can correspond to multiple observers. When the observer changes, he can notify all the observers one by one. Based on the interface, rather than the specific implementation ------ this provides more flexibility for the program.

For example, the cat woke up and scared away the mouse. This example can be implemented in the Observer mode. The cat is the observer, and the master and the mouse are the observer. The implementation class diagram is as follows:

                     

 

C # code implementation:

Public interface IObserver

{

Void Update ();

}

Public interface ISubject

{

Void AddObserver (IObserver obs );

Void RemoveObserver (IObserver obs );

Void y ();

}

Public class Mouse: IObserver

{

Public void Update ()

{

Console. WriteLine ("Mouse is escaped ");

}

}

Public class Master: IObserver

{

Public void Update ()

{

Console. WriteLine ("Master is waken ");

}

}

Public class Cat: ISubject

{

List <IObserver> list = new List <IObserver> ();

Public void AddObserver (IObserver obs)

{

List. Add (obs );

}

Public void RemoveObserver (IObserver obs)

{

List. Remove (obs );

}

 

Public void Policy ()

{

Console. WriteLine ("Cat is crying ");

Foreach (IObserver obs in list)

{

Obs. Update ();

}

}

}

Static void Main (string [] args)

{

IObserver mouse = new Mouse ();

IObserver master = new Master ();

ISubject cat = new Cat ();

Cat. AddObserver (mouse );

Cat. AddObserver (master );

Cat. Sort y ();

}

 

In. NET, using events and delegation to implement the Observer mode is simpler and a better solution. In the C # event, the delegate acts as an abstract Observer interface, and the object that provides the event acts as a target (Subject) object. In fact, the delegate is more loosely coupled than the abstract Observer interface, because the delegate only requires that the declaration part of the mounted method must conform to the format of the delegate declaration, you do not need to require classes to be fully implemented like interfaces. The observer mode is called the observer mode not because ISubject and IObserver are used internally, but because it solves the following problems: "The Observer mode defines a one-to-many dependency between objects, so that every time an object changes its state, the objects dependent on it will be notified and automatically updated ". That is to say, all solutions to this problem can be called the observer mode. In addition, the concept of interfaces is definitely not limited to interfaces in C #. interfaces are just a contract to regulate code behavior. delegate is also an interface, it specifies the method that can be loaded to the event corresponding to the delegate. This is also a contract, but this contract is simpler than the interface.

The following code uses the delegate event mechanism to implement the above functions:

Public class Cat

{

Public delegate void policyeventhandler ();

Public event policyeventhandler policyevent;

Public void Policy ()

{

If (policyevent! = Null)

{

Console. WriteLine ("Cat is crying ");

Yyevent ();

}

}

}

Public class Master

{

Public void Update ()

{

Console. WriteLine ("Master is waken ");

}

}

Public class Mouse

{

Public void Update ()

{

Console. WriteLine ("Mouse is escaping ");

}

}

 

Static void Main (string [] args)

{

Cat cat = new Cat ();

Master master = new Master ();

Mouse mouse = new Mouse ();

Cat. policyeventhandler policymaster = new Cat. policyeventhandler (master. Update );

Cat. policyeventhandler policymouse = new Cat. policyeventhandler (mouse. Update );

Cat. policyevent + = policymaster;

Cat. policyevent + = policymouse;

Cat. Sort y ();

}

Application scenarios:

  1. To update the status of an object, you must synchronously update other objects, and the number of other objects can dynamically change.
  2. Objects only need to notify other objects of their updates, without the need to know the details of other objects.

Advantages:

  1. Subject and obserer are sent and coupled, which can be changed independently.
  2. When a Subject sends a broadcast notification, it does not need to specify the specific Observer. The Observer can decide whether to subscribe to the Subject notification.
  3. Comply with most GRASP principles and common design principles, with high cohesion and low coupling.

Disadvantages:

  1. If a Subject is subscribed to by a large number of Observer users, it may be efficient during broadcast notifications.

Principles

We know that design principles are far more important than models. When learning design patterns, we must be aware of the concept of design principles. Now let's look at the design principles that all observer patterns comply.

  1. Identify the aspects of your application that vary and separate them from what stays the same (locate the changed part in the system and separate the changed part from other stable parts ). in the Application scenario of the Observer mode, the changes are the status of the Subject and the number of observers. The Observer mode can be used to isolate the two parts. We can change the number of Observer without modifying Subject, and the status of Subject can also be changed, it will not affect its Observer.
  2. Program to an interface, not an implementation (interface-oriented programming instead of implementation programming) Subject and Observer both use interfaces. Subject only needs to trace the objects that implement the IObserver interface, so it only depends on IObserver. All observers register, undo, and receive notifications through the ISubject interface, all of them only depend on ISubject; therefore, they are interface-oriented. This implementation makes Subject and Observer completely independent of any coupling.
  3. Favor composition over inheritance (Object combination is preferred, rather than class inheritance) Observer mode uses Object combination to associate Subject with several observers. The relationship between them is not inherited by class but a dynamic combination at runtime.

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.