This article is from: Cao shenghuan blog column. Reprinted please indicate the source:Http://blog.csdn.net/csh624366188
The observer mode is one of the behavior modes. It is used to automatically notify other associated objects and refresh the object status when the status of an object changes. The observer mode provides a synchronous communication method for associated objects to ensure the State synchronization between an object and other objects dependent on it. The design patterns book describes observer as follows:Defines a one-to-many dependency between objects. When the status of an object changes, all objects dependent on it will be notified and automatically updated.. Alias: dependents and publish-subscribe ).
Let's take a look at the components of the observer mode.
1) Abstract target role (subject): The target role knows its observer. Multiple observers can observe the same target. It also provides interfaces for registering and deleting observer objects. The target role is often implemented by abstract classes or interfaces.
2) Abstract observer role (observer): defines an update interface for objects that need to be notified when the target changes. Abstract observer roles are mainly implemented by abstract classes or interfaces.
3) a specific target role (concrete subject): stores the relevant status into each concrete observer object. When its status changes, a notification is sent to its various observers.
4) A specific observer role (concrete observer): stores the relevant status, which should be consistent with the target status. The observer update interface is implemented to make its status consistent with that of the target. This role can also maintain a reference pointing to the concrete subject object.
The structure is as follows:
Advantages and disadvantages of observer mode:
The observer mode has the following advantages:
First, the observer mode establishes an abstract coupling between the observer and the observer. What the observer role knows is a specific observer list. Each specific observer conforms to an abstract observer interface. The observer does not know any specific observer, but only knows that they all have a common interface.
Since the observer and observer are not closely coupled, they can belong to different abstract layers. If the object is thrown together by both the observer and the observer, the object must span the abstract and concrete layers.
Second, the observer mode supports broadcast communication. The observer will send a notification to all registered observers,
The observer mode has the following Disadvantages:
First, it takes a lot of time to notify all observers if they have many direct and indirect observers.
Second, if there is a circular dependency between the observer, the observer will trigger a circular call between them, resulting in system crash. Pay special attention to this when using the observer mode.
Third, if the notification to the observer is asynchronously delivered through another thread, the system must ensure that the delivery is carried out in the correct way.
Fourth, although the observer pattern can enable the observer to know that the observed object has changed at any time, the observer pattern does not have a mechanism to let the observer know how the observed object has changed.
The following procedure describes the observer mode:
A random number generates an object and two observers, both of which are registered in the random number generation object, meaning that if you generate a new number, let me know.
Structure:
Class description
Name |
Function Description |
Observer |
Indicates the observer interface. To become an observer, you must implement this interface. |
Numbergenerator |
Indicates the abstract class that generates values. |
Randomnumbergenerator |
Class that generates random numbers, inherited from numbergenerator |
Numberobserver |
A digital observer prints a changed number. |
Symbolobserver |
Symbol observer, print n symbols, and how many symbols are printed, determined by the accepted value |
1. Observer
package com.pattern.observer;public interface Observer {public abstract void update(NumberGenerator generator);}
2. numbergenerator
Package COM. pattern. observer; import Java. util. arraylist; import Java. util. iterator; /*** @ project javapattern * @ author sunnylocus * @ Verson 1.0.0 * @ date Aug 27,200 8 1:35:34 * @ Description: The abstract class that generates values */public abstract class numbergenerator {private arraylist observers = new arraylist (); // store observer/** add Observer */Public void addobserver (Observer observer) {observers. add (observer);}/** Delete Observer */Public void delobserver (Observer observer) {observers. remove (observer);}/** notify all Observers */Public void policyobservers () {iterator it = observers. iterator (); While (it. hasnext () {observer o = (observer) it. next (); O. update (this); // This is equivalent to the Post Office name} public abstract int getnumber (); // obtain the public abstract void generate (); // generate a number}
3. randomnumbergenerator
Package COM. pattern. observer; import Java. util. random; /*** @ project javapattern * @ author sunnylocus * @ Verson 1.0.0 * @ date Aug 27,200 8 1:48:03 * @ Description: class used to generate random numbers and notify Observers */public class randomnumbergenerator extends numbergenerator {private random = new random (); // random number generator private int number; // used to store the public void generate () {for (INT I = 0; I <5; I ++) {number = random. nextint (10); // generate a random number of less than 10 notifyobservers (); // a new number is generated, notify all registered observers}/** to obtain the number */Public int getnumber () {return number ;}}
4. numberobserver
Package COM. pattern. observer;/** indicates the observer class in numbers */public class numberobserver implements observer {public void Update (numbergenerator generator) {system. out. println ("numberobserver:" + generator. getnumber (); try {thread. sleep (1000*3); // sleep for 3 seconds to clearly see the output .} Catch (interruptedexception e) {e. printstacktrace ();}}}
5. symbolobserver
Package COM. pattern. observer;/** indicates the observer class with symbols */public class symbolobserver implements observer {public void Update (numbergenerator generator) {system. out. print ("symbolobserver:"); int COUNT = generator. getnumber (); For (INT I = 0; I <count; I ++) {system. out. print ("* ^_^ *");} system. out. println (""); try {thread. sleep (1000*3);} catch (interruptedexception e) {e. printstacktrace ();}}}
6. Main (test class)
Package COM. pattern. observer; public class main {public static void main (string [] ARGs) {// instantiate the number to generate the object numbergenerator generator = new randomnumbergenerator (); // instantiate the observer observer1 = new numberobserver (); Observer observer2 = new symbolobserver (); // register the observer generator. addobserver (observer1); generator. addobserver (observer2); generator. generate (); // generate number }}
7. result output