Object-oriented design pattern (vii), observer pattern

Source: Internet
Author: User

It seems that all design patterns are designed so that the program has low coupling, high flexibility, good expansibility, clear program structure and so on. Today's design pattern-the observer pattern is no exception, but the clarity of the program structure may not be the point. Well, the nonsense is less, the pattern of this simple and rude things still have to learn quickly, the following directly into the topic.

definition: The Observer pattern is a relationship between an object and an object before it is set to a one-to-many (not one-to-many) of the bean, so that when a party's state changes, all the many parties automatically change according to the change of one party.

Usage scenarios:

    1. Event-level triggering. such as a company, the CEO is the topmost observer (one side), observing the CEO has multiple managers, such as: Multiple General manager (more than one side) while observing the CEO, and each general manager can be observed by a number of other managers, such as: Project manager, product manager, etc., Then the general manager here is the Observer is also a level two observer, then as long as the CEO, the relevant general manager will make changes, and the general manager may have to let the bottom of the project manager and business manager to make changes, this is the event multilevel trigger;

    2. Associative binding behavior, the association behavior can be split, that is, unbind, not "combination", that is, two behaviors are independent of each other, not a whole;

    3. Cross-system message exchange scenarios, such as Message Queuing, event bus processing mechanisms.

Advantages:

    1. Enhance the flexibility and extensibility of the program;

    2. Reduce program coupling.

Disadvantages:

    • Since this pattern is actually a collection of all the Observer's references by the Observer, then iterating through the collection invokes the update method for each observer. Therefore, this results in the development efficiency and operational efficiency of the problem. Also, usually the traversal is sequential, so all observers are not actually making updates at the same time. What's more, if one of the observers updates is stuck, then the next observer will delay making the update, in which case it usually takes a multithreaded asynchronous approach, however, bringing new problems-concurrency.

The following first implements the observer pattern through the Observer class and Observable of the JDK itself

code implementation (using JDK built-in objects):

Observed by:

import java.util.Observable;/** * 被观察者 * @author lt * */publicclass BeObservered extends Observable{    /**     * 提交改变,调用Observable的setChanged()和notifyObservers();     * 注意:必须调用setChanged(),然后notifyObservers()才有效     */    publicvoidpostChanged(Object news){        // 标识被被观察者有新的改变        setChanged();        // 通知所有的观察者        notifyObservers(news);    }}

Note

    • Postchanged () is our own way of writing;
    • The setchanged () and notifyobservers () observers must be called in this method at the same time to accept the change, that is, the callback update method.

Observed by:

Importjava.util.Observable;ImportJava.util.Observer;/** * Viewer * @author LT * * / Public  class myobserver implements Observer{    PrivateString name; Public Myobserver(String name) { This. name = name; }/** * @param observable The observer observed by the Observer is beobservered * @param beobservered call Notifyobservers (OBJ ECT Arg) when passed the arg parameter * /    @Override     Public void Update(Observable Observable, Object News) {System.out.println (name+"Accept the change."+", the updated content is:"+news); }@Override     PublicStringtoString() {return "Myobservername="+ name +"]"; }}

? Here are some simple feedback in the update method.

Test:

 Public  class Test {     Public Static void Main(string[] args) {Myobserver Observer1 =NewMyobserver ("Xiao Ming"); Myobserver Observer2 =NewMyobserver ("Xiao Li"); Myobserver Observer3 =NewMyobserver ("Xiao Qiang"); beobservered beobervered =NewBeobservered ();//Add to Viewer queueBeobervered.addobserver (Observer1);        Beobervered.addobserver (OBSERVER2); Beobervered.addobserver (OBSERVER3);//Submit ChangesBeobervered.postchanged ("2016, Happy New Year!" "); }}

? Today is the first day of the New Year 2016, wishing everyone a happy New year, all the best!

Results:

The result needless to say, everyone gives feedback (haha, the article likes, the comment is also quite cool).

Using the JDK built-in object to implement the observer pattern, we can actually implement the observer pattern ourselves. Let's implement the observer pattern for ourselves.

Custom Implementation Viewer mode:

Observed by:

ImportJava.util.HashSet;ImportJava.util.Set;/** * Custom Observer * @author LT * * / Public  class Observable {     PublicSet<observer> observers =NewHashset<observer> (); Public Booleanischanged;//default = False     Public void Addobserver(Observer o) {//Prevent multithreading        synchronized(observers)        {Observers.add (o); }    } Public void setchanged(){ This. ischanged =true; } Public void notifyobservers(Object Arg) {if(ischanged) {//Iterate through the collection, notifying all observers in turn             for(Observer observer:observers) {Observer.update ( This, ARG); } ischanged =false;//Reset}    } Public void notifyobservers() {Notifyobservers (NULL); }}

Observed by:

publicinterface Observer {    publicvoidupdate(Observable observable, Object news);}

OK, the custom Implementation Viewer mode is complete, and the myobserver and beobservered imported JDK Observer and observable are converted to our own writing, run test tests.

Results:

? and the JDK with the observer and observable is the same, once again I wish you a happy new Year, everything, all the best!.

OK, here we define the implementation of the observer pattern is complete, is not feeling good simple, is a callback. In fact, here is not simple, it certainly involves a lot of things, what optimization ah, security ah what. We write the class on the above to do a synchronous processing, the other did not do, we can also go to see the JDK source code, see how it is done.

Summarize:

The main function of the observer pattern is for object decoupling, based on an abstract interface (easy to expand)Observer and Observable, to completely separate the observer from the observed (low coupling), to achieve all the observers that correspond when the observed change occurs Choose to make a change. This has a lot of uses, such as our Android to develop a software download market and so on need different activity can also need to see the same software download progress, and the ListView also used in this mode and so on. At the same time, knowing the principle of this pattern, we can also define our own observers and the observed.

Object-oriented design pattern (vii), observer pattern

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.