The observer pattern for Java design Patterns

Source: Internet
Author: User

Today I learned a bit about the observer pattern and summed it up.

What is the Observer pattern?

Observer pattern: Defines a one -to-many dependency between objects, and when an object's state changes, all objects that depend on it are notified and automatically updated.

The observer pattern is also called "dependent" or "publish-subscribe" mode. Give some examples of what an observer pattern is.

For example, between the subscriber and the press is the target (subject) and the Observer (Observer) relationship. Each Subscriber is the equivalent of an observer, and these observers are dependent on the publisher, and when the state of the publishing house changes to a new journal, all subscribers who depend on it will be notified and will receive the latest press.

For example in our program, the relationship between data and interface. A Table object and a Histogram object can use different representations to describe the information of the data object of the same application. When the information of the data object changes, the data in these interfaces will also be changed. There is no dependency between the Table object and the bar chart object.

participant in the Observer pattern :

    • Subject (target)
      The target knows its observer, but does not know who it is. There can be any number of observers observing the same target.
      Provides an interface for registering and deleting observation objects
    • OBSERVER (Observer)
      Defines an update interface for objects that need to be notified when a target changes.
    • ConcreteSubject (Specific target)
      To deposit the status of the Concretsubject object
      When its state changes, give notice to his individual observers.
    • Concreteobserver (Specific observer)
      Maintains a reference to a Concretesubjec object.
      Store related states, align these states with the state of the target
      Implements the Observer update interface to align its state with the state of the target.

Why use Observer mode?

Splitting a system into a class in which the columns work together has a side effect: the consistency between related objects needs to be maintained. At this point, it is not easy to maintain consistency between them, because they are tightly coupled, interdependent, and thus less reusable. The observer pattern is loosely coupled, so reusability can be improved.

When do I use observer mode?

    • When an object model has two facets, one aspect depends on the other. The two are encapsulated in separate objects so that they can be independently changed and reused.
    • When a change to an object needs to change other objects at the same time, it is not known how many objects need to be changed.
    • When an object must notify other objects, he cannot assume that other objects are who. In other words, we don't want these objects to be tightly coupled.

How to use Observer mode ?

This is illustrated by an example below.

 

/* * Publishing House Abstract Interface  */public interface Subject {    //remove observers     public void Removeobserver (Observer o);    //add observer     public void Addobserver (Observer o);     //Notification viewer     public void Notifyobservers ();} /* Specific target objects are assumed here as "reader Publishing house" */public class ConcreteSubject implements Subject{private arraylist<observer> observers; Private String book;public ConcreteSubject () {observers = new arraylist<observer> ();} @Overridepublic void Removeobserver (Observer o) {int i= observers.indexof (o), if (i>=0) {observers.remove (i);}} @Overridepublic void Addobserver (Observer o) {observers.add (o);} @Overridepublic void Notifyobservers () {for (Int. i=0;i<observers.size (); i++) {Observers.get (i). Update (book);}} How to change the state information when a new book is available This method can be used to add public void SetState (String book) {this.book = books;} By this method the Subscriber (Observer) can proactively get the target (subject) in the public String getState () {return book;} /* * Observer's abstract interface, with an update () method when the target (subject) state changesCall this method */public interface Observer {public void update (String book) when changing /* * Subscribers common Interface Zhang San and John Doe subscribers must implement this interface because they have a common method of display */public interface Displayelement {public void display ();}  /* Subscribers John Doe */public class Observer1 implements Observer,displayelement{private Subject subject;private String book;public Observer1 (Subject Subject) {this.subject = Subject;subject.addobserver (this);} @Overridepublic void Update (String book) {This.book = Book;display ();} @Overridepublic void Display () {System.out.println ("Observer1 received a new book:" +book);}}  /* Subscribers Zhang San */public class Observer2 implements Observer,displayelement{private String book;private Subject subject;public Observer2 (Subject Subject) {this.subject = Subject;subject.addobserver (this);} @Overridepublic void Update (String book) {This.book = Book;display ();} @Overridepublic void Display () {System.out.println ("Observer2 received a new book:" +book);}} public class Observertest {public static void main (string[] args) {ConcreteSubject subject = new ConcreteSubject (); obseRver1 Zhangsan = new Observer1 (subject); Observer2 lisi = new Observer2 (subject); Subject.setstate ("Reader's first issue"); Subject.notifyobservers ();}}




The observer pattern for Java design Patterns

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.