. The design pattern in NET Five: Observer mode

Source: Internet
Author: User
Tags final
The Design Observer pattern (Observer) perfectly separated the observer from the observed object. For example, the user interface can be used as an observer, the business data is observed, the user interface observes the changes in the business data, and when the data changes, it is displayed in the interface. One of the principles of object-oriented design is that each class in the system focuses on one function, not the other. An object does only one thing and does it well. The observer pattern defines clear boundaries between modules, increasing the maintainability and reusability of the application.

There are many ways to implement the observer pattern, which in essence must contain two roles: The Observer and the observed object. In just the example, the business data is the observed object, and the user interface is the Observer. There is a logical connection between the observer and the observed, and when the observer changes, the Observer observes the change and responds accordingly. If you use such an observation process between the user interface and the business data, you can ensure that the interface and data are in a different way, assuming that the requirements of the application change, you need to modify the performance of the interface, only need to rebuild a user interface, the business data need not be changed.

"Observation" is not "call directly"

When realizing the observer pattern, it should be noted that the interaction between the observer and the observed object can not be directly called between classes, otherwise it will cause the observer and the observed object to be tightly coupled and fundamentally violate the principle of object-oriented design. Neither the Observer "observes" the observer, or the observer notifies the observer of his change, should not be called directly.

Examples of implementing observer patterns

There are many forms of implementation of the observer pattern, the more intuitive one is the use of a "registration-notice-revocation registration" form. The following three graphs describe in detail such a process:

1: The Observer (OBSERVER) registers itself with the observed object (Subject), and the observed object stores the viewer in a container (Container).



2: The observed object has undergone some sort of change (as shown in the Askpricechanged), from which all registered observers are notified and the observer is informed of the change.



3: The observer tells the observed to revoke the observation, which is removed from the container by the Observer.



When the observer registers himself in the observer's container, the observer should not interfere with the specific type of observer, but should use the observer's interface. The advantage is that there are other observers in the program, so long as the observer is the same interface implementation. An observed person can correspond to multiple observers, and when the observed changes, he can notify all the observers of the message. interfaces, rather than concrete implementations, provide greater flexibility for the program.

The following code is an example of using C # to implement the Observer pattern:

"Observer" interface
Public interface IObserver {
void Notify (object anobject);
}

The observed object interface
Public interface IObservable {
void Register (IObserver anobserver);
void Unregister (IObserver anobserver);
}

Both the observer and the observed object are implemented separately from these two interfaces, all of which are defined by the two interfaces, rather than the concrete implementations. So the observer is not bound together with the observed object. We can conveniently change the observer and any part of the object being observed without affecting the other parts.

The following implements the specific object being observed. The following class is the base class for all observed objects, and implements the methods that are necessary for all objects being observed. We use a hashtable as the observer's container. The code is as follows:

Base class for all objects being observed
public class Observableimpl:iobservable {

Save the container for the observation object
protected Hashtable _observercontainer = new Hashtable ();

Registered Observer
public void Register (IObserver anobserver) {
_observercontainer.add (Anobserver,anobserver);
}

Revocation Registration
public void Unregister (IObserver anobserver) {
_observercontainer.remove (Anobserver);
}

Notify an observer of an event
public void Notifyobservers (object anobject) {
Enumerate the observers in the container and notify them of event one by one
foreach (IObserver anobserver in _observercontainer.keys) {
Anobserver.notify (AnObject);
}
}
}

The above class is not the final object to be implemented, but the base class of all the observers, which implements the functionality shared by all the observed objects. This class can simply be defined as abstract so that the programmer cannot create its instance. Interfaces and virtual classes that implement this interface both maintain loose coupling between classes and enable multiple implementations to use the same functionality.

The following is the final implementation of the observer pattern, using the user interface-business data as an example:

Business data (observed objects)
public class Somedata:observableimpl {
The data in the person being observed
float _askprice;

Changing the properties of a data
Public float Askprice {
set {
_askprice = value;
Base. Notifyobservers (_askprice)//will change the message notify the Observer
}
}
}
User Interface (Observer)
public class Somekindofui:iobserver {
public void Notify (object anobject) {
Console.WriteLine ("The New ask:" + anobject);
}
}

The procedure that is actually invoked
public class mainclass{
public static void Main () {
Create the observer and the person being observed
Somekindofui UI = new Somekindofui ();
Somedata data = new Somedata ();

Registering the Observer in the object being observed
Data. Register (UI);

Changing the data in the observed object, the observer informs the Observer
Data. Askprice = 1000f;

Log off observer, stop observing
Stock. Unregister (Stockdisplay);
}
}


. The better way to implement in net

The form above is that we implemented the observer pattern in a most basic way, and we developed a specific type for the Observer pattern. In the. NET Framework, you can better implement the observer pattern with proxies and events. C # In the introduction of agents and events can see this article: in C # in the way the agent to trigger the event, which has a detailed description of the agent and events, as well as routines, there is no more to say. There are also implementations in other languages that are supported by. NET.

In the mode of the event, the class that declares the event is the observed person. The observer does not need to register with the Observer, just expose an event without doing anything. The observer also does not need to register itself with the observation object, but rather to create an instance of a particular proxy that binds the agent to a method. Register or revoke the Observer's observation of the observed object in such a manner. Careful study of agents and event patterns is not difficult to find, the IObserver and IObservable interface method can reduce the coupling between the observer and the observed object, while the agents and events almost eliminate the coupling between the two modules, flexibility improved a lot.

Reference documents

Explore the Observer design pattern 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.