0. Ma Xian inspirational
It's not difficult to endure those hard days, because I know it will get better.
1. General
definition:
Also known as Publish/Subscribe mode, it defines a one to many dependency that allows 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:
- Subject: abstract topic (Abstract observer). The abstract topic role saves all observer objects in a collection. Each topic can have any number of observers. The abstract topic provides an interface to add and delete observer objects.
- ConcreteSubject: a specific subject (specific observer). This role stores the relevant status in the specific observer object. When the internal status of a specific subject changes, it sends a notice to all registered observers.
- Observer: Abstract observer is an abstract class of observer. It defines an update interface to update itself when notified of topic change.
- Concreteobserver: a concrete observer, which implements the update interface defined by the abstract observer, so as to update its own status when notified of the subject change.
3. Case realization
The official account of WeChat
When official account is official, we will have this experience. When new content is updated in your official account, it will be sent to WeChat users who are interested in the official account number. The WeChat public address is also available. We use the observer mode to simulate such scenes. WeChat users are observers. WeChat official account is the observer. Many WeChat users are concerned about the official account of program ape.
Class diagram is as follows:
The code is as follows:
Define the abstract Observer class, which defines an updated method
public interface Observer { void update(String message); }
Define a specific Observer class. Wechat users are observers, which implements the update method
public class WeixinUser implements Observer { // Wechat user name private String name; public WeixinUser(String name) { this.name = name; } @Override public void update(String message) { System.out.println(name + "-" + message); } }
Defines an abstract topic class and provides three methods: attach, detach, and notify
public interface Subject { //Add subscriber public void attach(Observer observer); //Delete subscriber public void detach(Observer observer); //Notify subscribers of update messages public void notify(String message); }
The official account of WeChat is a specific topic (the specific observer), which stores WeChat subscribers subscribing to the official account and implements the method of abstract topics.
public class SubscriptionSubject implements Subject { //Official account of WeChat subscribers private List<Observer> weixinUserlist = new ArrayList<Observer>(); @Override public void attach(Observer observer) { weixinUserlist.add(observer); } @Override public void detach(Observer observer) { weixinUserlist.remove(observer); } @Override public void notify(String message) { for (Observer observer : weixinUserlist) { observer.update(message); } } }
Client program
public class Client { public static void main(String[] args) { SubscriptionSubject mSubscriptionSubject=new SubscriptionSubject(); //Create wechat users WeixinUser user1=new WeixinUser("Sun WuKong"); WeixinUser user2=new WeixinUser("Pig Wuneng"); WeixinUser user3=new WeixinUser("Sha Wujing"); //Subscribing to official account mSubscriptionSubject.attach(user1); mSubscriptionSubject.attach(user2); mSubscriptionSubject.attach(user3); //Official account updates send messages to subscribers of WeChat subscribers. mSubscriptionSubject.notify("The column of Chuanzhi dark horse has been updated"); } }
4. Advantages and disadvantages
1. Advantages:
- It reduces the coupling relationship between the target and the observer, which is an abstract coupling relationship.
- When the observed sends a notice, all registered observers will receive the information [broadcast mechanism can be realized]
2. Disadvantages:
- If there are many observers, it will take time 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 scenario
- There is a one to many relationship between objects. The change of the state of one object will affect other objects.
- When an abstract model has two aspects, one of which depends on the other.
6. Implementation provided in JDK
In Java, observer mode is defined through java.util.Observable class and java.util.Observer interface. As long as their subclasses are implemented, observer mode instances can be written.
1. Observable class
Observable class is an abstract target class (observer). It has a Vector collection member variable to store all observer objects to be notified. The following describes its three most important methods.
-
void addObserver(Observer o) method: used to add a new observer object to the collection.
-
void notifyObservers(Object arg) method: call the update method of all observer objects in the collection to notify them of data changes. Usually, the later the observer joins the collection, the earlier the observer is notified.
-
void setChange() method: used to set an internal flag of boolean type to indicate that the target object has changed. notifyObservers() notifies observers only when it is true.
2. Observer interface
The Observer interface is an abstract Observer. It monitors the changes of the target object. When the target object changes, the Observer is notified and calls the update method to perform corresponding work.
The police caught the thief
The police can also use the observer mode to catch the thief. The police is the observer and the thief is the observed. The code is as follows:
The thief is an observer, so he needs to inherit the Observable class
public class Thief extends Observable { private String name; public Thief(String name) { this.name = name; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void steal() { System.out.println("Thief: I stole something. Is there anyone to catch me!!!"); super.setChanged(); //changed = true super.notifyObservers(); } }
The police is an Observer, so it needs to implement the Observer interface
public class Policemen implements Observer { private String name; public Policemen(String name) { this.name = name; } public void setName(String name) { this.name = name; } public String getName() { return name; } @Override public void update(Observable o, Object arg) { System.out.println("police:" + ((Thief) o).getName() + ",I've been staring at you for a long time. You can keep silent, but what you say will become evidence in court!!!"); } }
Client code
public class Client { public static void main(String[] args) { //Create thief object Thief t = new Thief("Lao Wang next door"); //Create police object Policemen p = new Policemen("petty thief"); //Let the police stare at the thief t.addObserver(p); //Thieves steal t.steal(); } }
This blog comes from the summary of dark horse programmer's video tutorial and the arrangement of notes. It is only for learning and communication. It should not be used for commercial purposes. If there is infringement, please contact the blogger to delete it. Blogger QQ: 194760901