Latest web development tutorials

Observer pattern

When there are many relationships between objects, use the observer pattern (Observer Pattern). For example, when an object is modified, it will automatically notify its dependent objects. The observer pattern belongs to behavioral patterns.

Introduction

Intent: define dependencies between objects of one-to-many, when the state of an object is changed, all objects that depend on it are notified and updated automatically.

Mainly to solve: a state of the object change notification to the problems of other objects, but also taking into account the ease of use and low coupling, ensure a high degree of collaboration.

When to use: an object (target object) changes state, all dependent objects (objects observer) will be notified, broadcast notification.

How to fix: use object-oriented technology, this dependency can be weakened.

The key code: abstract class have a ArrayList stored observers.

Application examples: 1, when the auction, the auctioneer observe the highest price, and then notify other bidders bid.2, Journey to the West inside Wukong request surrender Red Boy Buddha, Buddha water spilled over the floor of an old tortoise provoke, this turtle is the observer, he observed that action Buddha watering.

Advantages: 1, the observer and the observed are abstract coupled.2, to establish a trigger mechanism.

Disadvantages: 1, if the observed object has a lot of direct and indirect observer, it will notify all observers are to spend a lot of time.2, if there is a circular dependency between the observer and the observed target, observe the target will trigger calls to circulate between them, may cause the system to crash. 3, the observer mode there is no mechanism to let the viewer know the audience is how the observed changes, but just know that the observation target changes.

Usage scenarios: 1, multiple sub-class common method, and the same logic.2, important, complex methods can be considered as a template method.

Note: 1, JAVA already has observer mode support classes.2, to avoid circular references. 3, if the order of execution, a viewer can cause system errors stuck, generally use the asynchronous mode.

achieve

The observer pattern using three classes Subject, Observer and Client. Subject to the Client object with the object and the observer is bound observer methods tied Client Solutions from objects. We create theSubjectclass, Observer abstract class and extend the entity class abstractObserverclass.

ObserverPatternDemo,our demonstration classes using class objects and entitiesSubjectto demonstrate the Observer pattern.

The observer pattern UML diagram

step 1

Create Subject category.

Subject.java

import java.util.ArrayList;
import java.util.List;

public class Subject {
	
   private List <Observer> observers 
      = New ArrayList <Observer> ();
   private int state;

   public int getState () {
      return state;
   }

   public void setState (int state) {
      this.state = state;
      notifyAllObservers ();
   }

   public void attach (Observer observer) {
      observers.add (observer);		
   }

   public void notifyAllObservers () {
      for (Observer observer: observers) {
         observer.update ();
      }
   } 	
}

Step 2

Create Observer class.

Observer.java

public abstract class Observer {
   protected Subject subject;
   public abstract void update ();
}

Step 3

Create observer entity class.

BinaryObserver.java

public class BinaryObserver extends Observer {

   public BinaryObserver (Subject subject) {
      this.subject = subject;
      this.subject.attach (this);
   }

   @Override
   public void update () {
      System.out.println ( "Binary String:" 
      + Integer.toBinaryString (subject.getState ())); 
   }
}

OctalObserver.java

public class OctalObserver extends Observer {

   public OctalObserver (Subject subject) {
      this.subject = subject;
      this.subject.attach (this);
   }

   @Override
   public void update () {
     System.out.println ( "Octal String:" 
     + Integer.toOctalString (subject.getState ())); 
   }
}

HexaObserver.java

public class HexaObserver extends Observer {

   public HexaObserver (Subject subject) {
      this.subject = subject;
      this.subject.attach (this);
   }

   @Override
   public void update () {
      System.out.println ( "Hex String:" 
      + Integer.toHexString (subject.getState ()) .toUpperCase ()); 
   }
}

Step 4

UseSubjectand observer entity objects.

ObserverPatternDemo.java

public class ObserverPatternDemo {
   public static void main (String [] args) {
      Subject subject = new Subject ();

      new HexaObserver (subject);
      new OctalObserver (subject);
      new BinaryObserver (subject);

      System.out.println ( "First state change: 15");	
      subject.setState (15);
      System.out.println ( "Second state change: 10");	
      subject.setState (10);
   }
}

Step 5

Verify output.

First state change: 15
Hex String: F
Octal String: 17
Binary String: 1111
Second state change: 10
Hex String: A
Octal String: 12
Binary String: 1010