Design Pattern 5 in. Net: Observer Pattern

Source: Internet
Author: User

The observer mode perfectly separates the observer from the observed object. For example, the user interface can act as an observer. business data is observed. The user interface observes changes in business data and displays the changes on the interface. One principle of object-oriented design is that every class in the system focuses on a certain function, rather than other aspects. An object only does one thing and completes it. The observer mode clearly defines the boundaries between modules, improving the maintainability and reusability of applications.

The observer mode has many implementation methods. Basically, this mode must contain two roles:ObserverAndObserved object. In the preceding example, the business data is the observed object and the user interface is the observer. There is a logical association between the observer and the observer. When the observer changes, the observer will observe the change and respond accordingly. If such an observation process is used between the user interface and business data, the interface and data can be clearly defined. If the application needs to change, you need to modify the interface performance, you only need to re-build a user interface, and business data does not need to change.

"Observation" is not "direct call"

When implementing the observer mode, note that the interaction between the observer and the observed object cannot be reflected in direct calls between classes, otherwise, the close coupling between the observer and the observed object will fundamentally violate the object-oriented design principles. Neither the observer "observes" the object, nor the observer "notifies" the observer of the change.

Example of implementing the observer Mode

There are many ways to implement the observer mode. The more intuitive one is to use the form of "registration-Notification-Revocation of registration. The following three figures describe such a process in detail:

1: The Observer registers itself to the observed object (subject), which stores the observer in a container.

2: The observed object has a certain change (askpricechanged In). It obtains all registered observers from the container and notifies the observer of the change.

3: 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 should use the observer interface. This advantage is: if there are other observers in the program, as long as the observer is also 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 interfaces rather than specific implementations-This provides more flexibility for programs.

The following code uses C # To implement the observer mode:

// "Observer" Interface
Public interface iobserver {
Void notify (Object anobject );
}

// "Observed object" Interface
Public interface iobservable {
Void register (iobserver anobserver );
Void unregister (iobserver anobserver );
}

Both the observer and the observed object are implemented from these two interfaces. All operations are defined by these two interfaces, rather than the specific implementation. So the observer and the object to be observed are not bound together. We can easily change the observer and any part of the observed object without affecting other parts.

The following describes the objects to be observed. The following class is the base class of all observed objects and implements the required methods for all observed objects. We use a hashtable container as the observer. The Code is as follows:

// All base classes of the observed object
Public class observableimpl: iobservable {

// Save the container of the observed object
Protected hashtable _ observercontainer = new hashtable ();

// Register the observer
Public void register (iobserver anobserver ){
_ Observercontainer. Add (anobserver, anobserver );
}

// Cancel registration
Public void unregister (iobserver anobserver ){
_ Observercontainer. Remove (anobserver );
}

// Notify the observer of the event
Public void policyobservers (Object anobject ){
// Enumerate the observers in the container and notify them of the events one by one
Foreach (iobserver anobserver in _ observercontainer. Keys ){
Anobserver. Notify (anobject );
}
}
}

The above class is not the final object to be observed, but the base class of all the objects to be observed, which implements the functions shared by all the observed objects. This class can be simply defined as abstract, so that programmers cannot create their instances. Interfaces and virtual classes that implement these interfaces not only maintain loose coupling between classes, but also allow multiple specific implementations to use the same functions.

The following is an example of implementing the observer mode:

// Business data (observed object)
Public class somedata: observableimpl {
// The data in the Observer
Float _ askprice;

// Change data attributes
Public float askprice {
Set {
_ Askprice = value;
Base. notifyobservers (_ askprice); // notify the observer of the changed message.
}
}
}

// User Interface (observer)
Public class somekindofui: iobserver {
Public void notify (Object anobject ){
Console. writeline ("the new ask price is:" + anobject );
}
}

// Actual call Process
Public class mainclass {
Public static void main (){
// Create the observer and the observer
Somekindofui UI = new somekindofui ();
Somedata DATA = new somedata ();

// Register the observer in the observed object
Data. Register (UI );

// Change the data in the observed object. Then, the observed object will be notified to the observer.
Data. askprice = 1000f;

// Unregister the observer and stop the observer
Stock. unregister (stockdisplay );
}
}

. Net

The above form is that we have implemented the observer mode in the most basic way, and we have developed a specific type for the observer mode. In the. NET Framework, using proxies and events can better implement the observer mode. C # Introduction to middleware and events can be found in this article: in C #, the event is triggered by proxy, which contains a detailed description of proxy and event, as well as routines, I will not talk about it here. Other languages supported by. Net also have their own implementation methods.

In the event mode, the class that declares the event is the observer. The observer does not need to register the observer, but only needs to publish an event without performing any operation. The observer does not need to register himself to the observed object. Instead, he wants to create an instance for a specific proxy and bind the proxy to a method. Register or revoke the observer's observation on the object in this way. By carefully studying the proxy and event modes, it is not difficult to find that the iobserver and iobservable interfaces can reduce the coupling between the observer and the observed object, proxy and event almost eliminate the coupling between the two modules, improving flexibility a lot.

References

Explore Observer Design Patterns Doug Purdy (Microsoft Corporation) Jeffrey Richter (wintellect)

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.