[Design mode] observer Mode 2

Source: Internet
Author: User

• 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 will notify all observer objects so that they can automatically update themselves.

• Composition of the observer Mode
-Abstract topic role: stores 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 or interface.
-Abstract observer role: defines an interface for all specific observers and updates themselves when receiving notifications of the topic.
-Specific topic role: when the internal status of a specific topic changes, a notification is sent to all registered observers. A topic role is usually implemented using a subclass.
-Specific observer role: this role implements the update interface required by the abstract observer role to coordinate its status with the topic status.
If necessary, a specific observer role can save a reference pointing to a specific topic role. It is usually implemented using a subclass.

• Implement your own observer Mode

• Observer mode plays an important role in Java
• JDK also provides built-in support for the observer Mode

• 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.

• An object to be observed must follow the following two simple rules. First, if it is changed, it must call the setchanged () method.
Second, when it is ready to notify the observer of its changes, it must call the yyobservers () method.
This results in calling the update () method in the observed object.
Note: When the object does not call the setchanged () method before calling the yyobservers () method, no action will occur.
Before update () is called, the observed object must call the setchanged () and yyobservers () methods.

• Note that policyobservers () has two forms: one with parameters and the other without parameters. When the yyobservers () method is called with parameters, the update () method passed to the observer is used as the second parameter.
Otherwise, a null value is passed to the update () method. You can use the second parameter to pass any type of object suitable for your application.

• The Observer interface must be implemented to observe an object that can be observed. This interface only defines a method as follows.
-Void Update (observable observob, object Arg)
-Here, observob is the object to be observed, and Arg is the value passed by the yyobservers () method. When the observed object changes, call the update () method.

• Here is an example of an object that can be observed. This program creates a class called watcher, which implements the observer interface. The monitored class is called beingwatched, which inherits observable.
In beingwatched, It is the counter () method. This method is only used to reduce the count from a specified value. Every time the Count changes, the yyobservers () method is called, and the current count is passed as a parameter to the notifyobservers () method.
This causes the update () method in watcher to be called and the current Count value is displayed. In Main (), the watcher and beingwatched objects that call observing and observed are created.
Then, the observing is added to the list of observed observation programs. This means that the observing. Update () method will be called every time counter () calls the notifyobservers () method.
• See program observerdemo. Java

• Multiple objects can be used as observation programs. For example, the following program implements two observation classes and adds an object in each class to the beingwatched observation program list. The second observation program waits until the count is 0.
• See program twoobservers. Java

Watched. Java

 

1 package cn.itcast.observer1;2 3 public interface Watched{4     public void addWatcher(Watcher watcher);5     public void removeWatcher(Watcher watcher);6     public void notifyWatchers(String str);7 }

Concretewatched. Java

 1 package cn.itcast.observer1; 2  3 import java.util.ArrayList; 4 import java.util.List; 5  6 public class ConcreteWatched implements Watched{ 7     private List<Watcher> list = new ArrayList<Watcher>(); 8      9     public void addWatcher(Watcher watcher){10         list.add(watcher);11     }12 13     public void removeWatcher(Watcher watcher){14         list.remove(watcher);15     }16 17     public void notifyWatchers(String str){18         for(Watcher watcher : list){19             watcher.update(str);20         }21     }22 }

 

Observer's interface (abstract class) watcher. Java

1 package cn.itcast.observer1;2 3 public interface Watcher{4     public void update(String str);5 }

Concretewatcher. Java

1 package cn.itcast.observer1;2 3 public class ConcreteWatcher implements Watcher{4     public void update(String str){5         System.out.println(str);6     }7 }

Define two observers twoobservers. Java

1 package CN. itcast. observer1; 2 3 Import Java. util. observable; 4 Import Java. util. observer; 5 6 7 class beingwatched extends observable {8 void counter (INT number) {9 for (; number> = 0; number --) {10 this. setchanged (); 11 // change the Boolean Type member variable from false to true12 this. notifyobservers (number); 13 // when this method is called, the member variable is changed from true to false.14 // so that the next change will continue. 15 // these changes are reflected in the source code. 16 // The notifyobservers (number) method converts the set containing the observer (watcher) into an array. 17 // For (INT I = arrlocal. length-1; I> = 0; I --), first traverse the last 18 // so watcher2 is executed before watcher1. 19} 20} 21} 22 23 class watcher1 implements observer {24 public void Update (observable o, object Arg) {25 // This Arg is the above this. notifyobservers (number); the number in is the 26 System of the integer type. out. println ("watcher1's count is:" + Arg); 27} 28 29} 30 class watcher2 implements observer {31 public void Update (observable o, object Arg) {32 // determine the location 33 If (integer) Arg ). intvalue () <= 5) {34 system. out. println ("watcher2's count is:" + Arg); 35} 36} 37} 38 public class twoobservers {39 public static void main (string [] ARGs) {40 beingwatched watched = new beingwatched (); 41 42 watcher1 watcher1 = new watcher1 (); 43 watcher2 watcher2 = new watcher2 (); 44 45 watched. addobserver (watcher1); 46 watched. addobserver (watcher2); 47 48 watched. counter (10); 49} 50}

Test. Java

1 package CN. itcast. observer1; 2 3 Public class test {4 public static void main (string [] ARGs) {5 watched Girl = new concretewatched (); 6 7 watcher watcher1 = new concretewatcher (); 8 watcher watcher2 = new concretewatcher (); 9 watcher watcher3 = new concretewatcher (); 10 11 girl. addwatcher (watcher1); 12 girl. addwatcher (watcher2); 13 girl. addwatcher (watcher3); 14 15 girl. notifywatchers ("three people, happy"); 16 17 girl. removewatcher (watcher2); 18 19 girl. notifywatchers ("two people, unhappy"); 20} 21} 22/* 23 printed: 24 watcher1's count is: 1025 watcher1's count is: 926 watcher1's count is: 827 watcher1's count is: 728 watcher1's count is: 629 watcher2's count is: 530 watcher1's count is: 531 watcher2's count is: 432 watcher1's count is: 433 watcher2's count is: 334 watcher1's count is: 335 watcher2's count is: 236 watcher1's count is: 237 watcher2's count is: 138 watcher1's count is: 139 watcher2's count is: 040 watcher1's count is: 041 watcher2 is executed now, And watcher1 is executed later, because 42 is in watched. when addobserver () is used, watcher2 enters the home and is executed now. 43 */

Simple understanding:

Almost all event models in AWT and swing use the observer mode,

The observer mode defines the dependency between one (the button in the AWT) and multiple (when multiple listeners and buttons are clicked, multiple events are executed,
Let multiple observer objects listen to a single topic object at the same time (changes to the button of multiple listener listeners ).
When the status of this topic object changes (the button is clicked), all observer objects are notified,
Enable them to automatically update themselves.

Clicking a button to trigger an event automatically is not a matter of course. The button has an automatic event call mechanism behind it,

The button is a "topic", and there must be a set in the topic to store these listeners (or reference the listener ).
When you click this button, traverse the set and find the listener for this button.
Call the actionperform method in the listener for execution.

The method must be executed by the "topic". It must not be called automatically.
Many frameworks use the observer mode, and JDK also regards the observer mode as very important. It has built-in support APIs for the observer mode.

JDK in other modes is generally not supported, but this mode is used in some classes, but not in observer mode,
It even provides classes and interfaces and internal support.

[Design mode] observer Mode 2

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.