A comprehensive analysis of Java Observer pattern _java

Source: Internet
Author: User

Body

I. DEFINITION OF the Observer pattern:

Simply put, the Observer pattern defines a one-to-many dependency that allows one or more observer objects to listen to a Subject object. As a result, when the observer's state changes, it is necessary to notify the corresponding observer so that the observer objects can be updated automatically. For example, the event-handling mechanism in the GUI uses the Observer pattern.

II. implementation of the Observer model:

Subject (Object interface observed): A uniform interface for concretesubject; Each subject can have multiple observer;concretesubject (specifically observed): maintains a list of references to all specific observers; – Notifications are sent to all registered observers when the state changes. OBSERVER (Observer Interface): A uniform interface for Concreteobserver; defines an update () method that is invoked when the state of the object being observed changes. Concreteobserver (Specific observer): Maintain a reference to ConcreteSubject, specific state and ConcreteSubject synchronization, implementation observer interface, update () The role of the method: once the detection of subject changes, update the information.

The chart describes the following:

Note: There is a need for a set in the Observer class to maintain all observers.

Third, the example explains:

"Scenario One": define interfaces or classes to implement the observer pattern.

The steps are as follows:

(1) Define the interfaces that the observed person has:

Package com.vince.observer;
Public interface Observable {
 //registered as an observer public 
 void Registerobserver (Observer Observer);
 
 Cancels the Observer public 
 void Removeobserver (Observer Observer);
 
 Notifies all observers of update information public 
 void Notifyobservers ();
}

(2) The definition of specific observed persons: Cups

Package com.vince.observer;
Import Java.util.Vector;

public class Cup implements observable{
 //Observer object list maintained by observers
 private vector<observer> vector = new vector <Observer> ();
 private float price;
 
 Public Cup (float price) {
  This.price = Price;
 }
 
 public float GetPrice () {return price
  ;
 }
 public void Setprice (float price) {
  //Modify prices, notify all observers
  This.price =;
  Notifyobservers ();
 }
 @Override public
 void Registerobserver (Observer Observer) {
  //Registered Observer
  Vector.add (Observer);
 }
 @Override public
 void Removeobserver (Observer Observer) {
  //Cancel Observer
  Vector.remove (Observer);
 }
 @Override public
 void Notifyobservers () {
  //implementation notifies all observer objects for
  (Observer observer:vector) {
   Observer.update (price);}}


(3) Define the common interface that the Observer has: (Updating the data is, of course, done at the Observer's end)

Package com.vince.observer;

Public interface Observer {public

  void update (float price); 5 

}

(4) Defining the specific Observer object:

Package com.vince.observer;
public class person implements observer{
 private String name;
 Public person (String name) {
  this.name = name;
 }
 @Override public
 void update (float price) {
  System.out.println (name+) The prices of the cups concerned have been updated to: "+price);
 }


(5) Testing:

Package com.vince.observer;
public class Test {public
 static void Main (string[] args) {
  //Create a Viewer object
  cup doll = new Cup (3000);
  Create two observer objects person
  p1 = new Man ("Life One");
  person P2 = new Person ("Life II");
  Register to become an observer
  Doll.registerobserver (p1);
  Doll.registerobserver (p2);
  
  System.out.println ("First round of promotions:");
  Doll.setprice (2698);//Price change
  System.out.println ("Second round of promotions:");
  Doll.setprice (2299);//
  System.out.println ("Third round of promotions:");
  Doll.setprice (1998);
  
  Doll.removeobserver (p2); Remove life number second from
  System.out.println ("Fourth round promotions:");
  Doll.setprice (1098);  
  
 }


After running, the results appear as follows:

"Scenario Two": directly invoke the JDK API to implement.

The steps are as follows:

(1) Implement the specific observed object by inheriting the observable class:

Package com.vince.observer2;
Import java.util.Observable;

public class Cup extends observable{
 private float price;
 
 Public Cup (float price) {
  This.price = Price;
 }
 public float GetPrice () {return price
  ;
 }
 public void Setprice (float price) {
  This.price = Price;
  This.setchanged ()//notification, data has changed
  this.notifyobservers ();
 }
 
 


(2) Implement the specific observer object by implementing the Java.util.Observer interface:

Package com.vince.observer2;
Import java.util.Observable;
Import Java.util.Observer;

public class person implements observer{
 private String name;
 Public person (String name) {
  this.name = name;
 }
 @Override public
 void update (Observable o, Object Arg) {
  if (o instanceof Cup) {
   cup cup = (cup) o;
   System.out.println (name+ "The concerned Cup price has been updated to:" +cup.getprice ());}}}


(3) Testing:

Package com.vince.observer2;
public class Test {public
 static void Main (string[] args) {
  cup cup = new Cup (3000);
  person P1 = new Person ("life One");
  person P2 = new Person ("Life II");
  Cup.addobserver (p1);
  Cup.addobserver (p2);
  System.out.println ("First round of promotions");
  Cup.setprice (2988);
  System.out.println ("Second round of promotions");
  Cup.setprice (2698);
  
  Cup.deleteobserver (p2);
  System.out.println ("Third round of promotions");
  Cup.setprice (1998);
 }


After running, the results are as follows:

"Engineering Documents"

Link: Http://xiazai.jb51.net/201609/yuanma/JavaSEguancha (jb51.net). rar

Iv. Summary: (role of observer model)

The Observer pattern creates an abstract coupling between the observer and the Observer. What the observer role knows is a list of specific observers.

Because the observer and the observer are not tightly coupled, they can belong to different levels of abstraction. If both the observer and the observer are thrown together, the object must transcend the abstraction and materialization level.

Observer mode supports broadcast communications. The observer will give notice to all the registered observers.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.