March 25, 2019 11:01:22
Observer pattern
The words written in the front
During the golden three silver four job hopping season, design mode is also one of the frequently asked questions. In an interview on March 2, I asked about design mode, asked about observer mode, and asked to write pseudo code. At that time, the first thing in my mind was big talk design mode An example of this is the collective desertion of employees. The sister at the front desk is responsible for notifying everyone when the boss comes back. At that time, she stammered and wrote the code reluctantly. To her surprise, she passed two sides. Go back and review it.
definition
There will be such a day in the world, when you come to their world, they will become your lifelong subscribers, happy with you and sad with you.
Observer mode defines a one to many dependency, which allows multiple observer objects to listen to a topic object at the same time. When the status of the topic object changes, it will notify all observer objects so that they can update themselves automatically. -- Design Mode: basis of Reusable Object-Oriented Software
Observer mode is an object behavior mode.
Usage scenario
When the change of one object (noun) needs to change (verb) other objects.
What problems can observer mode solve:
- 1. One to many dependencies between objects should be defined without tight coupling of objects
- 2. You should ensure that unlimited dependent objects are automatically updated when an object changes.
- 3. One object should be able to notify unlimited other objects.
In the second case, message middleware is one of the implementations. When a producer sends a message, unlimited consumers get the message and automatically update themselves.
Third, publish subscribe push mode. WeChat official account should be representative. When content is updated, the subscriber will be notified.
role
Abstract Subject: defines the methods commonly used by the observer, including the functions of attach, detach and notify
Concrete subject: a method that implements the definition of abstract topics, maintains a collection of observers through the attach and detach methods, and notifies all observers when their maintained state changes
Abstract Observer: defines a method to update itself
Concrete Observer: implement the method of updating your own
Illustration
Observer class diagram:

Observer sequence diagram:

Code example
The code example uses the example mentioned above. The employees leave collectively, and the little sister at the front desk is responsible for notifying everyone when the boss comes back.
Firstly, the front desk sister is the specific subject role, and the employee is the specific observer role. Secondly, the front desk sister maintains the observer set and notifies all observers when the boss comes back; the observer implements his own update method after the front desk sister notifies him. What should I do.
Abstract theme:
public interface Observable { public void attach(Observer observer); public void detach(Observer observer); public void notifyObservers(); }
Front desk sister (specific subject is the observed):
public class Receptionist implements Observable { private String state = "The boss is out"; private ArrayList<Observer> observers = new ArrayList<>(); public String getState() { return state; } public void setState(String state) { this.state = state; System.out.println(state); } @Override public void attach(Observer observer) { observers.add(observer); } @Override public void detach(Observer observer) { observers.remove(observer); } @Override public void notifyObservers() { observers.forEach(observer -> observer.update()); } }
Watch NBA employee Observer:
public class NBAObserver implements Observer{ @Override public void update() { System.out.println("Watching NBA Turn off the live broadcast NBA Live, work"); } }
Stock speculation employee Observer:
public class StockObserver implements Observer { @Override public void update() { System.out.println("Closing the stock market panel and working"); } }
Observer mode test class:
public class ObserverTest { public static void main(String[] args) { Receptionist mm = new Receptionist(); Observer nba = new NBAObserver(); Observer stock = new StockObserver(); mm.attach(nba); mm.attach(stock); // mm saw the boss coming back mm.setState("The boss is back"); // Notify employees who have subscribed mm.notifyObservers(); } }
Test results:

Note: it is clearly the front desk sister who is observing whether the boss has come back. Why is the front desk sister the observer?
The "boss is back" status is the internal status of the front desk sister. The observer mode is the relationship between objects. Observers watching NBA and stock speculation monitor the status of the front desk sister and update themselves when changes occur.
Observer pattern in Java class library
In the Java class library, java.util.Observer and java.util.Observable are used as observers and observers. Because of their limited role, they have been deprecated in Java 9.
advantage
- The loose coupling is realized on the premise that the change of one object needs to change other objects.
- Conform to the opening and closing principle, inherit the abstract topic to add the observed, inherit the abstract observer to add the observer.
shortcoming
- If an observation target 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 lead to system crash.
- The observer model has no corresponding mechanism to let the observer know how the observed target object has changed, but only know that the observed target has changed.
summary
Observer mode defines a one to many dependency, which allows multiple observer objects to listen to a topic object at the same time. When the status of the topic object changes, it will notify all observer objects so that they can update themselves automatically.
reference resources
Dahua design mode
finish
March 26, 2019 15:02:09