Design Pattern---observer pattern

Source: Internet
Author: User

Observer mode Observer (behavioral mode)

1. Overview

Observer pattern: Defines a one-to-many dependency between objects, so that whenever an object state changes, its dependent objects are notified and automatically updated.

Example 1: Drivers who drive as observers, traffic lights on the road as an observation target, when the color status of the traffic lights change, the driver is notified, and update his behavior.

Example 2: A page that can display the product information, when the information about the goods in the database changes, the page information will also change accordingly.

2. Structure diagram

3. Code

Code Description: When playing Warcraft game, teammates are attacked by the enemy, the map will have red flag hint, other teammates as observers, update their status, go to support.

1 Importjava.util.ArrayList;2 3 /*4 * Abstract observation target class5  */6  Public Abstract classSubject {7 8     //store all the specific observers9     protectedArraylist<observer> players =NewArraylist<observer>(); Ten      PublicSubject () { One          A     } -      -     //Join Method the      Public voidAttach (Observer obs) { -System.out.println (Obs.getname () + "join");  - Players.add (OBS);  -     }   +        -     //Exit Method +      Public voidDetach (Observer obs) { ASystem.out.println (Obs.getname () + "Exit");  at Players.remove (OBS);  -     }   -      -     //declaring an abstract notification method -      Public Abstract voidNotify (String name);  -  in}

1 /*2 * Specific observation target class3  */4  Public classConcreteSubjectextendsSubject {5 6      PublicConcreteSubject () {7         //TODO auto-generated Constructor stub8     }9 Ten @Override One      Public voidNotify (String name) { A         //iterate through the Observer collection, invoking an Update method for each observer (except itself) -          for(Object obs:players) { -             if(!( (Observer) obs). GetName (). Equalsignorecase (name)) {   the ( (Observer) obs). Update ();  -             }   -         }        -  +     } -  +}

1 /*2 * Abstract Viewer3  */4 InterfaceObserver {5 6      PublicString getName (); 7      Public voidsetName (String name); 8      Public voidupdate ();9      Public voidbeattacked (Subject s);Ten  One}

1 /*2 * Specific observers3  */4  Public classConcreteobserverImplementsObserver {5 6     PrivateString name;7      Publicconcreteobserver (String name) {8          This. Name =name; 9     }Ten @Override One      PublicString GetName () { A         return  This. Name; -     } - @Override the      Public voidsetName (String name) { -          This. Name =name; -  -     } +  -     //update your own status + @Override A      Public voidUpdate () { atSystem.out.println (name+ "to support"); -  -     } -  - @Override -      Public voidbeattacked (Subject s) { inSystem.out.println (name+ "attacked"); -S.notify ( This. Name); to  +     } -  the}

1  Public classTest {2 3      Public Static voidMain (string[] args) {4ConcreteSubject s =NewConcreteSubject ();5         6 Observer O1,o2,o3;7O1 =NewConcreteobserver ("a player");8O2 =NewConcreteobserver ("B player"));9O3 =NewConcreteobserver ("C Player"));Ten          One S.attach (O1); A S.attach (O2); - S.attach (O3); -          the o1.beattacked (s); -  -     } -  +}

4. Applicable scenarios

(1) Changing an object will cause one or more other objects to change, without knowing exactly how many objects will change or who they are.

(2) An abstract model has two aspects, one of which relies on another, encapsulating the two aspects in separate objects so that they can be independently changed and reused. Let both sides of the coupling rely on abstraction, rather than relying on specifics. So that their changes will not affect the change on the other side.

Design Pattern---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.