design mode (Java)--viewer mode

Source: Internet
Author: User

Turn from: The Dharma of slavery
http://blog.csdn.net/zhengzhb/article/details/7471978?reload#reply

definition: defines a one-to-many dependency between objects so that when each object changes state, all objects that depend on it are notified and updated automatically.

Type: behavior class mode

Class Diagram:

This is often required in software systems: if the state of an object changes, certain objects associated with it change accordingly. For example, we want to design a right-click menu function, as long as the software in the active area of the right mouse button, we will pop up a menu, for example, we want to design an automatic deployment of functionality, like Eclipse development, as long as the file is modified, eclipse will automatically deploy the modified file to the server. The two features have a similar place where one object listens to another object at all times, and as long as its state changes, it has to act accordingly. In fact, there are a lot of scenarios that can be achieved, but there is no doubt that using the observer pattern is a mainstream choice.

Structure of the Observer pattern

In the most basic observer pattern, the following four characters are included:

    • observed: from the class diagram, you can see that there is a vector container in the class that holds the Observer object (the reason that the vector is used instead of list is that the vector is secure when the multi-threaded operation is not safe and the list is unsafe). This vector container is the core of the Observer class, and there are three additional methods: The Attach method is to add the Observer object to the container, and the detach method is to remove the observer object from the container, and the Notify method is to call the corresponding method of the Observer object in turn. This role can be an interface, an abstract class, or a specific class, because in many cases it is mixed with other schemas, so the use of abstract classes is more likely.
    • Observer: The Observer role is generally an interface that has only one update method that is invoked when the observer state changes.
    • Specific Observer: This role is used for extensibility purposes, where specific business logic can be defined in this role.
    • specific Observer: the specific implementation of the Observer interface, in which the logic to be processed when the state of the Observer object is changed is defined.

Observer Pattern Code Implementation

 PackageTM;ImportJava.util.Vector;Abstract classSubject {PrivateVector<observer> Obs =NewVector<observer>();  Public voidaddobserver (Observer obs) { This. Obs.add (OBS); }     Public voiddelobserver (Observer obs) { This. Obs.remove (OBS); }    protected voidNotifyobserver () { for(Observer o:obs) {o.update (); }    }     Public Abstract voiddosomething ();}classConcreteSubjectextendsSubject { Public voiddosomething () {System.out.println ("The observed event is reversed.");  This. Notifyobserver (); }}InterfaceObserver { Public voidupdate ();}classConcreteObserver1ImplementsObserver { Public voidUpdate () {SYSTEM.OUT.PRINTLN ("Observer 1 receives the message and processes it. "); }}classConcreteObserver2ImplementsObserver { Public voidUpdate () {SYSTEM.OUT.PRINTLN ("Observer 2 receives the message and processes it. "); }} Public classClient { Public Static voidMain (string[] args) {Subject sub=NewConcreteSubject (); Sub.addobserver (NewConcreteObserver1 ());//Add Observer 1Sub.addobserver (NewConcreteObserver2 ());//Add Observer 2sub.dosomething (); }}
View Code

Run results

The observed event is reversed

Observer 1 receives the message and processes it.

Observer 2 receives the message and processes it.

By running the results we can see that we have only called the subject method, but at the same time the related methods of the two observers have been called simultaneously. A closer look at the code, in fact, is very simple, is simply to associate the Observer class in the subject class, and in the DoSomething method to traverse the Observer Update method on the line.

The advantages of the observer pattern

The observer and the observed are mildly correlated, and are abstract coupled, so that they are easier to extend for both.

The observer pattern is a common trigger mechanism that forms a trigger chain and then processes each observer's method in turn. But at the same time, this is a disadvantage of the observer pattern, because it is a chain trigger, when the observer is more, performance problems are more worrying. Moreover, in the chain structure, it is easy to make a circular reference error, causing the system to feign death.

Summarize

In the Java language, there is an interface observer, and its implementation class observable, which is often implemented for observer roles. We can see how these two classes are used in the JDK's API documentation.

A friend who has done VC + +, JavaScript dom, or AWT has been amazed by the handling of their events, and the observer pattern, which has a certain understanding of the principle of the event handling mechanism. Using the Observer pattern is a good choice if you want to design an event-triggering processing mechanism, and the event-handling Dem in AWT (delegate event model delegation) is implemented using the Observer pattern.

design mode (Java)--viewer mode

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.