The 18th chapter of the design pattern-Observer pattern (Java implementation)

Source: Internet
Author: User

The 18th chapter of the design pattern-Observer pattern (Java implementation)

  Say Zeng, that is chenhe these days some fire, then these stars most afraid of, the same favorite is what? Yes, it's the paparazzi. The name of the English is more interesting, is paparazzo, this statement is said to come from the Italian film "Dew Peony Open" in a special candid photo of a photographer's name, "Paparazzo", the Chinese translation of Paparazi, the saying is the paparazzi. These stars are proud of the paparazzi, get exposure, but also because of the paparazzi, was exposed to negative news, anyway, in short, "Fire up", so that the stars love and hate. (Everyone: Fish brother, you pull away). Well, this paparazzi, in fact, is the so-called surveillance observation activity, and then let the Observer tell us about the things that the observer and design patterns have to say.

Self-introduction of the Observer pattern

Yes, four. (I am) The Observer, also known as dependency or publish subscription, is a pattern that is often used in projects. The definition is as follows: Define a one-to-many dependency between objects so, then one objects changes state, all its dependents is Notifi Ed and updated automatically. Translates to the definition of a one-to-many dependency between objects, so that whenever an object changes state, all objects that depend on it are notified and automatically updated. The general class diagram of the Observer is as follows:

  

Self-analysis of the Observer pattern

First of all, the following benefits:

    • Supports broadcast communication.
    • Abstract coupling between the target and the observer.

  Then there is the disadvantage part:

    • Because an observer does not know the existence of other observers, it may be ignorant of the ultimate cost of changing the target.
    • Then there is the problem of efficiency, development efficiency and operational efficiency, there may be problems, an observer, a number of observers, development and debugging is more complex, and one observer is stuck, other observers will be affected.
    • In addition, the efficiency of multi-level triggering also needs to be taken into account.

The realization of the observer pattern

  As for the realization then take a "ozone" to raise a chestnut. Take Zeng to raise chestnuts (Yin elder brother, I do not mean, do not blame me, I know you are loler, play well), the first is to be observed observable, is celebrity, such as ozone big, Xi big, Linus big and so on:

1  Public Interfaceobeservable{2     //Increase the viewer3      Public voidaddobserver (Observer Observer);4     //Delete Viewer5      Public voiddeleteobserver (Observer Observer);6     //notify observers of changes7      Public voidnotifyobservers (String context);8}

This is the Universal observer interface, all observers can implement this interface, followed by the Little Yin Interface:

1  Public Interfaceizengxiaoxian{2     //Eat3      Public voideat ();4     //Sleep5      Public voidsleep ();6     //Play7      Public voidplay ();8}

  Little Yin's interface contains 3 activities, eating, sleeping, playing peas, ah, mouth slip, is playing, entertainment activities, such as Akiji out to play, and so on, the following is the specific implementation of the small virtuous class:

1  Public classZengxiaoxianImplementsizengxiaoxian,obserable{2     //define a dynamic array of paparazzi that hold different media3     PrivateArraylist<observer> observerlist =NewArraylist<>();4     //Increase the viewer5      Public voidaddobserver (Observer Observer) {6          This. OBSERVERLIST.ADD (Observer);7     }8     //Delete Viewer9      Public voiddeleteobserver (Observer Observer) {Ten          This. OBSERVERLIST.REMOVE (Observer); One     } A     //notify observers of changes -      Public voidnotifyobservers (String context) { -          for(Observer observer:observerlist) { the observer.update (context); -         } -     } -     //Eat +      Public voideat () { -System.out.println ("Zeng to eat"); +          This. Notifyobservers ("Zeng to eat"); A     } at     //Sleep -      Public voidsleep () { -System.out.println ("Zeng to sleep."); -          This. Notifyobservers ("Zeng's Going to bed"); -     } -     //Play in      Public voidPlay () { -System.out.println ("Zeng to play"); to          This. Notifyobservers ("Zeng to play"); +     } -}
View Code

  The Observer has realized, then the observer's implementation, and the observer's interface is still the first:

1  Public Interface observer{2     // When the observed person has movement, they begin to prepare the manuscript and make headlines. 3      Public void Update (String context); 4 }

and then it's the paparazzi, the paparazzi:

1  Public classPaparazzo1Implementsobserver{2     //Paparazzi Number One, once you find something, tell the boss.3      Public voidUpdate (String str) {4System.out.println ("See Zeng and Zhang Zixian kiss, start reporting");5          This. Reporttoxx (str);6     }7     //report to XX media8     Private voidReporttoxx (String context) {9System.out.println ("Boss, I see" +context);Ten     } One}

  If you want other paparazzi, please implement PAPARAZZO2, 3 and so on, then we use a scene class to achieve the situation at that time:

1  Public classclient{2      Public Static voidMain (string[] args) {3         //come out a paparazzi4Observer paparazzo =Newpaparazzo ();5 6         //Zeng Appearances7Zengxiaoxian Zengxiaoxian =NewZengxiaoxian ();8 Zengxiaoxian.addobserver (paparazzo);9 Ten         //Look what Zeng is doing. One zengxiaoxian.eat (); A Zengxiaoxian.play (); - zengxiaoxian.sleep (); -     } the}
View Code

  Well, the basic implementation is like this.

The application scenario of the Observer pattern

When you encounter any of the following situations, consider the use of the amount to achieve:

    • When an abstract model has two facets, one of them relies on another.
    • When a change to an object needs to change other objects at the same time, it is not known how many objects need to be changed.
    • When an object must notify other objects, it cannot assume that other objects are who.

  This time it's my turn to debut, Paparazzi is the amount, the four paparazzi, oh yes. "Dynamic two-action two, I am a move, here is a suspected mental hospital ran out of the patient, hurriedly give capture back", "Fish elder brother, save amount, amount is not mental illness, you tell them quickly." (Author by: Less one, so that after a few people and I rob snacks.) Left silently). Jin Clods Thorn qin King, design mode let me break.

PS: This blog welcome forwarding, but please specify the blog address and author ~

Blog Address: http://www.cnblogs.com/voidy/

Blog: http://voidy.net

<. ))) ≦

The 18th chapter of the design pattern-Observer pattern (Java implementation)

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.