Observer mode
1 Definition
Also known as publish subscribe mode, it defines a one to many dependency, allowing multiple observer objects to listen to a topic object at the same time. When the state of the subject object changes, it will notify all observer objects so that they can update themselves automatically.
2 Structure
There are the following roles in observer mode:
- Abstract topic (Abstract observed): the abstract topic role saves all observer objects in a collection. Each topic can have any number of observers. The abstract topic person provides an interface to add and delete observer objects
- Specific topic (specific observer): the specific topic role stores the relevant status into the specific observer object, and notifies all registered observers when the internal status of the specific topic changes
- Abstract Observer: it is the abstract class of the observer, which defines an interface to update itself when the subject changes
- Concrete Observer: implement the update interface defined by the abstract observer to update its own state when notified of the subject change
3 Implementation
WeChat official account official account: official account official account is used to show the experience of WeChat. When you have new contents updated in the official account, it will be sent to the WeChat users who are concerned about the public number. We use the observer mode to simulate such a scenario. The micro credit households are the observers, and the WeChat public number is the observer. Many WeChat users have paid attention to the official account of program ape.
package Design pattern.Behavioral model.Observer mode; //WeChat official account (abstract theme role) public interface Subject { //Add subscriber (add observer) void attach(Observer observer); //Delete subscriber (delete observer) void detach(Observer observer); //Notify subscribers of update messages void notify(String message); }
package Design pattern.Behavioral model.Observer mode; //User (Abstract observer) public interface Observer { void update(String message); }
//Specific subject role public class SubscriptionSubject implements Subject{ //Define a collection to store multiple observer objects private List<Observer> observers = new ArrayList<>(); @Override public void attach(Observer observer) { observers.add(observer); } @Override public void detach(Observer observer) { observers.remove(observer); } @Override public void notify(String message) { for (Observer observer : observers) { //Call the update method in the observer object observer.update(message); } } }
//Specific observer role public class WeiXinUser implements Observer{ private String name; public WeiXinUser(String name) { this.name = name; } @Override public void update(String message) { System.out.println(name + "-" + message); } }
//Test class public class Test { public static void main(String[] args) { //Create official account number SubscriptionSubject subject = new SubscriptionSubject(); //Subscribing to official account subject.attach(new WeiXinUser("Zhang San")); subject.attach(new WeiXinUser("Li Si")); subject.attach(new WeiXinUser("Wang Wu")); //The official account is updated to send messages to subscriber objects. subject.notify("It's updated. Come on"); } }
Test results:
Zhang San - updated, come and see
Li Si - updated, come and see
Wang Wu - updated, come and see
4 advantages and disadvantages
advantage:
- It reduces the coupling relationship between the target and the observer, which is an abstract coupling relationship
- When the observed sends a notification, all registered observers will receive a message (broadcast mechanism can be implemented)
Disadvantages:
- If there are many observers, it will be more time-consuming for all observers to receive the notification sent by the observed
- If the observer has circular dependency, the notification sent by the observer will make the observer call circularly, which will lead to system crash
5 usage scenarios
- There is a one to many relationship between objects. A change in the state of one object will affect other objects
- When an abstract model has two aspects, one of which depends on the other
6 JDK source code analysis
In Java, through Java util. Observable class and Java util. The observer interface defines observer patterns. You can write observer pattern instances as long as you implement their subclasses.
6.1 Observable
Observable class is an abstract target class (observer). It has a Vector collection member variable, which is used to save all observer objects to be notified. It provides three methods:
- void addObserver(Observer o) method: used to add a new observer object to the collection
- void notifyObjservers(Object o) method: call the update method of all observers in the collection to notify them that the data has changed. Generally, the later the observers join the collection, the earlier they are notified
- void setChange() method: used to set an internal flag of boolean type to indicate that the target object has changed. When it is true, notifyObjservers() will notify the observer
6.2 Observer
The Observer interface is an abstract Observer. When the target object changes, the Observer is notified and calls the update method to perform corresponding work.