This is the third day of my participation in the November Gwen Challenge. Check out the details: the last Gwen Challenge 2021

The Observer Pattern is used for one-to-many objects and automatically notifies dependent objects when an object is modified.

The observer model belongs to the behavioral model.

introduce

describe parsing
intentions Defines a one-to-many dependency between objects in which all dependent objects are notified and automatically updated when an object’s state changes.
Mainly to solve The problem of one object notifying other objects of state changes, with ease of use and low coupling in mind, ensuring a high degree of collaboration.
When to use When the state of an object (the target object) changes, all dependent objects (the observer object) are notified, broadcasting notification.
How to solve Using object-oriented technology, this dependency can be weakened.
The key code In the abstract class there is an ArrayList that holds observers.
Examples of application 1. During an auction, the auctioneer observes the highest bid and then notifies other bidders to bid. 2. Ancient beacons spread messages, lit beacons, and other observers made changes.
advantages The observer and the observed are abstractly coupled. 2. Build a trigger mechanism.
disadvantages 1. If an observed object has many direct and indirect observers, it can take a long time to notify all observers. 2. If there is a cyclic dependency between the observer and the observing target, the observing target will trigger a cyclic call between them, possibly causing the system to crash. 3. The observer mode has no corresponding mechanism to let the observer know how the observed object has changed, but only to know that the observed object has changed.
Usage scenarios 1. 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. 2, the change of one object will cause one or more other objects to change, and do not know how many objects will change, can reduce the degree of coupling between objects. 3. An object must notify other objects without knowing who they are. 4. You need to create A triggering chain in the system, where the behavior of object A affects object B, and the behavior of object B affects object C… You can use observer mode to create a chain trigger mechanism.
Matters needing attention JAVA already has classes that support the Observer pattern. 2. Avoid circular references. 3. If executed sequentially, an observer error will cause the system to jam, usually asynchronously.

implementation

This example provides three dependency classes to convert the changes to base 2, base 8, and base 16 respectively

1. Subject provides changes;

2, Observer abstract class

A, BinaryObserver

A) OctalObserver b) OctalObserver

C, HexObserver Hexadecimal conversion observer

3. ObserverPatternDemo, the scene class uses Subject and entity-class objects to demonstrate the observer pattern.

Step 1 –

Create the Subject class.

// 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(); }}}Copy the code

Step 2- Create the Observer abstract class

Create an Observer abstract class.

// Observer.java
public abstract class Observer {
   protected Subject subject;
   public abstract void update();
}
Copy the code

Step 3- Create the observer entity class

Create the entity Observer 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() ) ); }}Copy the code
// 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() ) ); 
   }
}
Copy the code
// HexObserver.java public class HexObserver 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() ); }}Copy the code

Step 4- Create the scene class

Create the ObserverPatternDemo to bind

// ObserverPatternDemo.java public class ObserverPatternDemo { public static void main(String[] args) { Subject subject = new Subject(); new HexObserver(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); }}Copy the code

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
Copy the code