Design Pattern (13) Observer pattern, design pattern Observer Pattern

Source: Internet
Author: User

Design Pattern (13) Observer pattern, design pattern Observer Pattern
Observer Mode Observer

The observer mode defines a one-to-many dependency, allowing multiple observer objects to listen to a topic object at the same time.

When the status of this topic object changes, it notifies all observer objects so that they can automatically update themselves.

Composition of observer Mode

Abstract topic role: Saves all references to the observer object in a collection. Each abstract topic role can have any number of observers. Abstract topic provides an interface to add and delete observer roles. It is generally implemented using an abstract class and interface.

Abstract observer role: Defines an interface for all specific observers and updates themselves when receiving notifications of a topic.

Specific topic roles: Send a notification to all registered observers when the internal status of a specific topic changes. A topic role is usually implemented using a subclass.

Specific observer role: This role implements the update interface required by the abstract observer role, so that its status can be consistent with that of the topic. It is usually implemented using a subclass. If necessary, a specific observer role can save a reference pointing to a specific topic role.

Code
// Abstract observer role public interface Watcher {public void update (String str );}

Define the abstract topic role, that is, the abstract observer, in which the declaration method (add, remove observer, notify Observer ):

// Abstract topic role, watched: Observed public interface Watched {public void addWatcher (Watcher watcher); public void removeWatcher (Watcher watcher); public void policywatchers (String str );}

Define the specific observer:

public class ConcreteWatcher implements Watcher{    @Override    public void update(String str)    {        System.out.println(str);    }}

Specific topic roles:

Import java. util. arrayList; import java. util. list; public class ConcreteWatched implements Watched {// stores the observer private List <Watcher> list = new ArrayList <Watcher> (); @ Override public void addWatcher (Watcher watcher) {list. add (watcher) ;}@ Override public void removeWatcher (Watcher watcher) {list. remove (watcher) ;}@ Override public void policywatchers (String str) {// automatic call is actually called by the topic for (Watcher watcher: list) {watcher. update (str );}}}

Compile the test class:

Public class Test {public static void main (String [] args) {Watched girl = new ConcreteWatched (); Watcher watcher1 = new ConcreteWatcher (); Watcher watcher2 = new ConcreteWatcher (); watcher watcher3 = new ConcreteWatcher (); girl. addWatcher (watcher1); girl. addWatcher (watcher2); girl. addWatcher (watcher3); girl. notifyWatchers ("happy ");}}
Observable class

The Observable class is used to create subclasses that can observe other parts of your program. When the object of this subclass changes, the observation class is notified.

The observation class must implement the Observer interface that defines the update () method..

The update () method is called when an observation program is notified of a change to the observed object.

Apparently,Observable is an abstract topic object..

An object to be observed must follow the following two simple rules:

First, if it is changed, it must callSetChanged ()Method.

Second, when it is ready to notify the observer of its changes, it must callYyobservers ()Method, which leads to the call to the update () method in the observed object.

Note:: If the setChanged () method is not called before the yyobservers () method is called, no action will occur.

The yyobservers () method contains the clearChanged () method, which sets the flag variable back to the original value.

The yyobservers () method uses the Traversal method from the back to the front. That is, the added observer is called the update () method first.

Code

Defines a theme object for reciprocal counting. Each time a number changes, its observer receives this number.

One observer prints a number after receiving the notification, and the other observer starts printing when the number is smaller than or equal to 5.

Import java. util. observable; import java. util. observer; class WatchedCounter extends Observable {public void countdown (int number) {for (; number> = 0; -- number) {// set the variable setChanged (); // notify all observers to pass the number as the parameter information to the Observer notifyObservers (number) ;}} class Watcher1 implements Observer {@ Override public void update (Observable arg0, Object arg1) {System. out. println ("Watcher1's number:" + arg1) ;}} class Watcher2 implements Observer {@ Override public void update (Observable arg0, Object arg1) {if (Integer) arg1 ). intValue () <= 5) {System. out. println ("Watcher2's number:" + arg1) ;}} public class ObserverTest {public static void main (String [] args) {WatchedCounter watchedCounter = new WatchedCounter (); watcher1 watcher1 = new Watcher1 (); Watcher2 watcher2 = new Watcher2 (); // Add the observer watchedCounter. addObserver (watcher1); watchedCounter. addObserver (watcher2); // starts the Countdown count watchedCounter. countdown (10 );}}
I am the dividing line of tiantiao

 

 

Reference: http://www.cnblogs.com/mengdd/archive/2013/02/08/2909206.html


What is "Observer Design Pattern" in java "?

The Observer Pattern is also known as the publish/subscribe mode. It is one of the software design modes. The observer mode defines a one-to-many dependency between objects. When the State of an object changes, all objects dependent on it are notified and automatically updated.
In observer mode, a target object (observer) manages all observer objects dependent on it and actively sends notifications when its status changes, this is usually done by calling the methods provided by various observers. This mode is usually used to implement an event processing system. The observer mode has many implementation methods. Basically, this mode must contain two roles: the observer and the observer. The interaction between the observer and the object to be observed cannot be reflected in the direct call between classes, which will closely couple the observer and the object to be observed, this fundamentally violates the object-oriented design principles. In specific implementation, we need to develop interface-oriented programming to allow the observer to manage the observer object interface type, and then call the interface method to update the observer.

For details, refer to "software tips: Design Patterns". I hope you can learn the design patterns as soon as possible!
 
Java Design Pattern observer pattern code

First
Public interface RandomNumberListener {// interface
Public void numberChanged (double d );
}

Second
Public class Consol implements RandomNumberListener {

@ Override
Public void numberChanged (double d ){
System. out. println (d );
}

}

Third
Public class SwingWindow
Extends JFrame
Implements RandomNumberListener {// observer
Private JLabel label = new JLabel ();
Public SwingWindow (){
This. getContentPane (). add (label );
This. setSize (300,200 );
This. setVisible (true );
}

@ Override
Public void numberChanged (double d ){
Label. setText (String. valueOf (d ));
}

}

Fourth
Public class RandomNumber {// business
Private double r;
Private List <RandomNumberListener> listeners = new ArrayList <RandomNumberListener> ();

// Add all observers
Public void addRandomNumberListener (RandomNumberListener lis ){
Listeners. add (lis );
}

Public void random (){
R = Math. random ();
// The data changes and all observers are notified.
For (RandomNumberListener lis: listeners ){
Lis. numberChanged (r );
}
}
}

Fifth
Public class Test {
Public static void main (String [] args) throws InterruptedException {
RandomNumber rn = new RandomNumber ();

SwingWindow sw = new SwingWindow ();
Consol c = new Consol ();

Rn. addRandomNumberListener (sw );
Rn. addRandomNumberListener (c );

While (true ){
Rn. random ();
Thread. sleep (new Random (). nextInt (3000) + 1000L );
}
}

}... Remaining full text>

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.