Example tutorials for using observer patterns in Java design pattern development _java

Source: Internet
Author: User

The Observer pattern is one of the software design patterns, and is more common, especially in GUI programming. On the design model of the article, the network wrote more, and a lot of writing is good, although there is a repetition of the early wheel of suspicion, but this wheel is not that wheel, the focus is different, the idea is different, the way is not nearly the same.
key Elements

Theme:

Subject is the object observed by the observer, a subject must have the following three characteristics.

    • A reference to the observer who holds the listener
    • Support for adding and removing observers
    • Subject state changes, informing the Observer

Observed by:

When the subject changes, it is the characteristic that the observer must possess to receive the notification for specific treatment.

Why do you use this pattern?

Here is an example to illustrate that milk delivery station is the theme, milk customers for the listener, customers from the milk station subscription milk, will receive milk every day. If the customer does not want to subscribe, it can be canceled and will not receive milk later.

Loose coupling

The observer adds or deletes code that does not need to modify the subject, simply by invoking the corresponding addition or deletion method of the subject.
The subject is responsible only for notifying the observer, but does not need to know how the observer handles the notification. For example, the milk delivery station is only responsible for delivery of milk, do not care whether the customer is drinking or washing face.
The observer simply waits for the subject to be notified without observing the relevant details of the subject. Or that example, the customer only care about sending milk station to milk, do not care about the milk by which courier personnel, the use of what kind of transportation service.

Java Implementation Observer mode
1. Java Self-band implementation
class Diagram

/** * Observation target inherits from Java.util.Observable * @author Stone * * * * public class Updateobservable extends observable { 
   
  private int data; 
    Public updateobservable (Observer Observer) {addobserver (Observer); 
  * * ADD other Observer */} public int GetData () {return data; 
      public void SetData (int data) {if (data!= this.data) {this.data = data; Setchanged (); Mark Change, only mark can be notified to Notifyobservers (); 
  Notification} @Override public synchronized void Addobserver (Observer o) {super.addobserver (o); 
  @Override public synchronized void Deleteobserver (Observer o) {super.deleteobserver (o); 
  @Override public void Notifyobservers () {super.notifyobservers (); 
  @Override public void Notifyobservers (Object arg) {super.notifyobservers (ARG); 
  @Override public synchronized void Deleteobservers () {super.deleteobservers (); 
 }
  @Override protected synchronized void setchanged () {super.setchanged (); 
  } @Override protected synchronized void clearchanged () {super.clearchanged (); 
  @Override Public Synchronized Boolean haschanged () {return super.haschanged (); 
  @Override Public synchronized int countobservers () {return super.countobservers (); 

 } 
   
}
/** 
 * Observer implements JAVA.UTIL.OBSERVER interface 
 * @author stone */Public 
class Updateobserver implements Observer { 
 
  @Override public 
  void update (Observable o, Object Arg) { 
    System.out.println ("Notification of data Changes received:"); 
    if (o instanceof updateobservable) { 
      updateobservable uo = (updateobservable) o; 
      System.out.print ("Data Change to:" + uo.getdata ());}} 
 
 

2. A custom observation model
class Diagram

/** * 
 abstract Observer  Observer 
 * Observation Update     
 * @author Stone * * * * public 
interface Iwatcher { 
  * 
   * Notification Interface: 
   * 1. Simple Notice 
   * 2. The observer needs the change of the target data, then the target can be used as a parameter, see Java Observer and Observable/ 
/Void Update (iwatched watched); 
   
  void Update (); 
   
} 

/** 
 * Abstract Objective Subject 
 * Provides an interface for registering and deleting observer objects, and for notifying observers of the interface * 
 and the target's own observed business 
 * @author Stone 
 * 
 * Public 
interface Iwatchedsubject {public 
   
  void Add (Iwatcher watch); 
 
  public void Remove (Iwatcher watch); 
   
  public void Notifywhatchers (); 
   
  public void Update ()//interface for observed business changes 
} 

/** 
 * Specific observer    concrete Observer 
 * 
 * @author stone */Public 
class Updatewatcher Implements Iwatcher { 
 
  @Override public 
  Void Update () { 
    System.out.println (this + observes: Target has been updated); 
  } 
 
} 


/** 
 * Specific target role  concrete Subject 
 * @author Stone * * * Public 
class Updatewatchedsubject Implements Iwatchedsubject { 
  private list<iwatcher> List; 
   
  Public Updatewatchedsubject () { 
    this.list = new arraylist<iwatcher> (); 
  } 
   
  @Override public 
  void Add (Iwatcher watch) { 
    this.list.add (watch); 
  } 
 
  @Override public 
  void Remove (Iwatcher watch) { 
    this.list.remove (watch); 
  } 
 
  @Override public 
  void Notifywhatchers () {for 
    (Iwatcher watcher:list) { 
      watcher.update (); 
    } 
  } 
   
  @Override public 
  Void Update () { 
    System.out.println ("Target update ..."); 
    Notifywhatchers (); 
  } 
 
 


A listener is an implementation of a viewer:
Class diagram

/** 
 * Monitoring user after registration 
 * @author Stone * * * * public 
interface Iregisterlistener { 
  void Onregistered (); 
} 

/** 
 * Monitor when the user logs in * @author stone * * * * * public 
interface Iloginlistener { 
  void onlogined () 
} 

* 
 * listener is an implementation of the Observer mode 
 * Some need to listen to the business interface to add listeners, call the corresponding method of the listener, to implement the listener/public 
class User {public 
   
  void Register (Iregisterlistener Register) { 
    / 
     * * Do ... register 
    /System.out.println ("in Registration ..."); 
    After registration 
    register.onregistered (); 
  } 
 
  public void Login (Iloginlistener login) { 
    / 
     * * Do ... login 
    /System.out.println ("Login ..."); 
    After login 
    login.onlogined (); 
  } 
 
 


/** * Observer (Observer) mode behavioral pattern * Observer mode defines a One-to-many dependency that allows multiple observer objects to observe a target object simultaneously. 
   
  * When the target object changes in state, it notifies all the observer objects so that they can automatically update themselves * target object needs to add, remove, notify the observer of the interface * * @author Stone * * public class Test { public static void Main (string[] args) {/* Use Java self-contained observer interface and observable class * * * UPDATEOBSERVABL 
    E observable = new updateobservable (new Updateobserver ()); 
    Observable.setdata (99); 
    System.out.println (""); 
    System.out.println (""); 
    * * Custom Observer Model * * Iwatchedsubject watched = new Updatewatchedsubject (); 
    Watched.add (New Updatewatcher ()); 
    Watched.add (New Updatewatcher ()); 
    Watched.update (); 
     
    System.out.println (""); 
    * * Sub Mode-listener/USER user = new user (); User.register (New Iregisterlistener () {@Override public void onregistered () {SYSTEM.OUT.P Rintln ("After hearing registration ...) 
      "); 
    } 
    }); 
   User.login (New Iloginlistener () {@Override   public void onlogined () {System.out.println after login ... 
      "); 
     
  } 
    }); 
 } 
}


Print

Notification of data changes received: 
data change to: 
 
target update .... 
Observer. Updatewatcher@457471e0 observed that the target has been updated 
Observer. UPDATEWATCHER@5FE04CBF observed: The target has been updated to be 
 
registered ... 
After hearing the registration ... 
Logging in ... 
Supervisor hears after login ... 

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.