Design Pattern discovered in. Net Class Library: Observer Pattern

Source: Internet
Author: User

Observer mode:

The Observer Pattern Defines a one-to-define dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically. (The Observer mode defines a one-to-many dependency between objects, so that every time an object changes its state, all objects dependent on it will be notified and automatically updated)

 

Subject (object interface observed)

Specifies the unified interface of concretesubject;

Each subject can have multiple observers;

Concretesubject (object to be observed)

Maintains a list of references to all specific observers;

When the status changes, a notification is sent to all registered observers.

Observer (Observer Interface)

Specifies the unified interface of concreteobserver;

Defines an update () method, which is called when the state of the object to be observed changes.

Concreteobserver (Specific observer)

Maintain a reference to concretesubject;

Synchronization between the specified status and concretesubject;

Implement the observer interface to receive concretesubject notifications through the update () method.

 

Applications in the. NET Framework

Like the [Rule mode], the observer mode is also widely used. It can be seen in almost all the places where one-to-many information needs to be synchronized, but the specific manifestation may be slightly different. Here, let's take another example in. the example of using the observer mode in. NET is actually very simple and everyone must have used it. That is, the "Delegate/event mechanism" in C #. 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, delegation is a more loosely coupled design than the abstract observer interface, because delegation only requires that the famous part of the attached method must conform to the delegated reputation format, you do not need to require classes to be fully implemented like interfaces. Speaking of this, some friends (the observer of this article) may have some questions. The interface is interface in C #, and the delegate is delegate. How can they get together? To answer this question, we need to consider the philosophy of the design model. The observer mode is called the observer mode, not because isubject is used internally.
Iobserver and other classes to implement the Code with the structure shown in Figure 2 above, but because this pattern solves the following problem: "The Observer Pattern Defines a one-to-many dependency between objects, so that every time an object changes its state, all objects dependent on it will be notified and automatically updated. "That is to say, all methods to solve this problem can be called observer mode. In addition, the interface concept is definitely not limited to the interface in C #. The interface is just a contract to regulate code behavior. The delegate is also an interface, it specifies the method that can be loaded into the event. This is also a contract, but this contract is simpler than interface.

If you were in ASP. if you have written programs in net and winform, you may have used delegation and events. The event is subejct, and the delegate is observer, let's take a look at the example of the observer Mode Implemented by using events:

Public class subject
{
Public subject (){}
Public eventhandler event1;

Public void raiseevent1 ()
{
If (event1! = NULL)
Event1 (null, null );
}
}

Public class observer
{
Public observer (subject s)
{
S. event1 + = new eventhandler (handlemethod );
}

Public void handlemethod (Object OBJ, eventargs E)
{
Console. writeline ("observer is done ");
}
}

The form button control exposes a click event that can be notified to the observer when the button is clicked. Any observer that needs to respond to the event only needs to register a delegate (New eventhandler (handlemethod) to the event) is a delegate, registering a delegate is + = to event1 event ). The form button control does not depend on any potential observer. Every observer only needs to know the delegate signature format of this event and is OK (in this instance, the delegate is eventhandler ), because eventhandler is a delegate type rather than an interface, each observer does not need to implement an extra interface. If an observer already has a method that complies with the delegate signature format, then it just needs to register this method to the subject event. By using delegation and events, the observer mode can decouple the subject from the observer (that is, the subject does not need to explicitly call a method of the observer )!

 

Application scenarios and advantages and disadvantages:

The above has already made a more detailed introduction to the observer model. In other words, there is no perfect person, and the model is not omnipotent. We should use the design model to solve our actual problems, you must be familiar with the application scenarios and advantages and disadvantages of the Mode:

Application scenarios of observer mode:

1. Update the status of an object. Other objects must be updated synchronously, and the number of other objects can be changed dynamically.

2. The object only needs to notify other objects of its own updates without knowing the details of other objects.

Advantages of observer mode:

1. Subject and observer are loosely coupled and can be changed independently.

2. When a subject sends a broadcast notification, it does not need to specify a 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.

Observer pattern defects:

1. Loose coupling causes the code relationship to be less obvious and sometimes hard to understand. (Nonsense)

2. If a subject is subscribed by a large number of observer users, it may be efficient during broadcast notifications. (After all, it is just a simple traversal)

Principles

I believe everyone should be clear about the observer model now! OK! As we have repeatedly stressed in the previous article, the design principles are far more important than the patterns. When learning the design patterns, you must be aware of the application of the design principles. Here, let's take a look at the design principles in the Observer mode.

1. Identify the aspects of your application that vary and separate them from what stays the same. (find 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. (For interface programming, not for implementation programming .)

Both Subject and observer use interfaces. Subject only needs to trace the objects that implement the iobserver interface, so it only depends on iobserver. All observers use the isubject interface to register, undo, and receive notifications, therefore, they only depend on isubject. Therefore, this is interface-oriented. This implementation makes subject and observer completely decoupled.

3. Favor composition over inheritance. (Object combination is preferred, rather than class inheritance)

The observer mode uses Object combinations to associate subject with several observers. The relationship between them is not inherited by class but a dynamic combination at runtime.

Reference: http://www.cnblogs.com/zhongkeruanjian/archive/2006/03/18/352766.html

Http://www.cnblogs.com/justinw/archive/2007/05/02/734522.html

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.