Java design pattern-Observer Pattern)

Source: Internet
Author: User

The observer mode is widely used in software programming. I am not good at expressing the stories I have seen on the internet, and I want to explain the basic ideas with examples of my life.

Story:

Xiaoxue is a very beautiful girl. Pretty girls always have many pursuers, and their teams are constantly changing. At any time, some people enter this team and quit. When boys pursue girls, they always show 120% of their concerns. When Xiaoxue enjoys the game without permission, they always receive messages from the pursuers asking about the location change of Xiaoxue. Xiaoxue is also annoying, but Xiao Xue is such a kind girl. She always interrupts her normal life and replies to the boys. The boys are exhausted by constantly worrying about the changing position of light snow, which also affects normal work. What did we find in such a simple story scenario? Let's take a look at the troubles of snow and boys:
1. Boys must constantly ask about changes in the position of the light snow to interrupt normal work;
2. Xiaoxue also needs to constantly accept the inquiry from boys. Sometimes, the position of Xiaoxue has not changed. It is still necessary to continuously reply to the inquiry from boys, which also affects normal work.

3. if there are different ways for boys to reply to questions, Xiao Xue also needs to know different ways of replying, and new boys are constantly increasing, I still don't know what new reply methods will be available in the future.

Seeing so many troubles, our creative Nokia company has proposed solutions for Xiao Xue and boys:
Nokia honors a mobile phone with the GPRS function, which stores a list of phone numbers that subscribe to location change text message notifications, when the mobile phone detects a location change, it will send text messages to all the mobile phones in the subscription list. Seeing the Nokia solution, boys and Xiao Xue should be relieved. They can communicate with each other only when their status changes.

 

The observer pattern can also be expressed by an example in life, that is, reading a magazine from the post office. Assume that a girl named Nini has subscribed to the magazine "fashion girl" at the post office and the magazine "Zhiyin" at the B post office, and told the two post offices that, if the magazine arrives, call me and I will get it by myself. Then the Post Office will register the girl's name, phone number, and other information in the system. The rest of Nini is waiting for the post office to call the magazine. If the magazine arrives, the post office calls Nini and says, "If your magazine arrives, please go to a certain post office to retrieve it (this is equivalent to referencing the object in the program-post office name, and passing it to the observer ), if you only want to say that your magazine has arrived, please go to the post office to get it. How can Nini know which post office to get the magazine.

The following program imitates the above situation. A Random Number produces an object and two observers. Both observers 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 (); // stores the observer
/** Add an Observer */
Public void addobserver (Observer observer ){
Observers. Add (observer );
}
/** Delete the 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 mentioned above
}
}
Public abstract int getnumber (); // obtain a number
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 refers to the class used to generate random numbers and notify the observer.
*/
Public class randomnumbergenerator extends numbergenerator {
Private random = new random (); // random number generator
Private int number; // used to store numbers

Public void generate (){
For (INT I = 0; I <5; I ++ ){
Number = random. nextint (10); // generate a random number of less than 10
Yyobservers (); // a new number is generated to notify all registered observers.
}
}
/** Get 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 a number to generate an object
Numbergenerator generator = new randomnumbergenerator ();
// Instantiate the observer
Observer observer1 = new numberobserver ();
Observer observer2 = new symbolobserver ();
// Register the observer
Generator. addobserver (observer1 );
Generator. addobserver (observer2 );

Generator. Generate (); // generate a number
}
}

7. Test Results

Design Philosophy:

The observer mode defines one-to-many dependencies between objects. When the status of an object changes, all its dependent objects will be automatically notified and updated.

Python: http://blog.csdn.net/sunyonggao/archive/2009/03/08/3970299.aspx

From: http://sunnylocus.javaeye.com/blog/233212

Related Article

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.