Java single application - Architecture Mode - 03. Design mode - 20. Observer mode

Original address:
More tutorials: Beam cloud - free course

Observer mode

Serial number Chapter in text video
1 Summary -
2 Realization -

Please refer to the navigation above for reading

1. overview

When there is a one to many relationship between objects, Observer Pattern is used. For example, when an object is modified, its dependent objects are automatically notified. The Observer Pattern belongs to behavioral pattern.


Defines a one to many dependency between objects. When the state of an object changes, all objects that depend on it are notified and automatically updated.

Main solutions:

The problem that an object state changes to inform other objects, and easy to use and low coupling should be considered to ensure a high degree of cooperation.

When to use:

When the state of an object (target object) changes, all dependent objects (observer object) will be notified and broadcast.

How to solve:

This kind of dependency can be weakened by using object-oriented technology.

Key code:

In the abstract class, there is an ArrayList for the observers.

Application example:

  • During the auction, the auctioneer observes the highest bid price and then informs other bidders to bid.
  • In the journey to the west, Wukong asks the Bodhisattva to surrender the red boy. The Bodhisattva sprinkles water to attract an old tortoise. The tortoise is the observer. He observes the action of the Bodhisattva sprinkling water.


  • The observer and the observed are abstractly coupled.
  • Set up a trigger mechanism.


  • If an observed object has many direct and indirect observers, it will take a lot of time to notify all observers.
  • If there is a circular dependency between the observer and the observation target, the observation target will trigger a circular call between them, which may cause the system to crash.
  • The observer model has no corresponding mechanism to let the observer know how the observed object changes, but only to know that the observed object has changed.

Usage scenario:

  • An abstract model has two aspects, one of which depends on the other. Encapsulate these aspects in separate objects so that they can be changed and reused independently.
  • The change of one object will lead to the change of one or more other objects. Without knowing how many objects will change, the coupling between objects can be reduced.
  • An object must notify other objects without knowing who they are.
  • You need to create A trigger chain in the system. The behavior of object A will affect object B, and the behavior of object B will affect Object C , you can use the observer pattern to create A chain trigger mechanism.

matters needing attention:

  • JAVA already has support classes for the observer pattern.
  • Avoid circular references.
  • If it is executed in sequence, a certain observer's error will cause the system to jam, which is generally asynchronous.

2. implementation

The Observer pattern uses three classes: Subject, Observer, and Client.

The Subject object has methods to bind and unbind observers to and from the Client object.

We create the Subject class, the Observer abstract class, and the entity class that extends the abstract class Observer.

Observer patterndemo, our demonstration class uses Subject and entity class objects to demonstrate observer pattern.

Step 1

Create the Subject class., the code is as follows:

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;

   public void attach(Observer observer){

   public void notifyAllObservers(){
      for (Observer observer : observers) {

Step 2

Create the Observer class., the code is as follows:

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

Step 3

Create the entity Observer class., the code is as follows:

public class BinaryObserver extends Observer{

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

   public void update() {
      System.out.println( "Binary String: " 
      + Integer.toBinaryString( subject.getState() ) ); 
}, the code is as follows:

public class OctalObserver extends Observer{

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

   public void update() {
     System.out.println( "Octal String: " 
     + Integer.toOctalString( subject.getState() ) ); 
}, the code is as follows:

public class HexaObserver extends Observer{

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

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

Step 4

Use Subject and entity observer objects., the code is as follows:

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");   
      System.out.println("Second state change: 10");  

Step 5

Execute the program and output the result:

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

Last article: Memo mode
Next article: State mode

If you are interested in the content of the course, you can scan the code to pay attention to our official account or QQ group, and pay attention to our curriculum updates in time.

Tags: Java

Posted on Fri, 13 Mar 2020 06:15:48 -0700 by st89