This is the 7th day of my participation in the November Gwen Challenge. Check out the details: The last Gwen Challenge 2021
An overview of the
Definition:
Also known as the Publish/Subscribe pattern, it defines a one-to-many dependency that allows multiple observer objects to listen on a subject object simultaneously. The topic object notifies all observer objects of state changes so that they can update themselves automatically.
structure
There are the following roles in Observer mode:
- Abstract topic roles store all observer objects in a collection. Each topic can have any number of observers. Abstract topics provide an interface to add and remove observer objects.
- ConcreteSubject: Concrete topic (concrete observed). This role stores the state in the concrete observer object and notifies all registered observers when the internal state of the concrete topic changes.
- Observer: An abstract class for an Observer that defines an update interface to update itself when notified of a topic change.
- ConcrereObserver: A concrete observer that implements an update interface defined by an abstract observer to update its own state when notified of a topic change.
Case implementation
Wechat official account
In the use of wechat public number, we will have such an experience, when you pay attention to the public number in the new content update, it will be pushed to the wechat user concerned about the public number. We use the observer mode to simulate such a scene. The wechat user is the observer, and the wechat public account is the observed. Multiple wechat users follow the official account of the Program ape.
The class diagram is as follows:
The code is as follows:
Define an abstract observer class that defines an updated method
public interface Observer {
void update(String message);
}
Copy the code
Define the specific observer class, wechat user is the observer, which implements the update method
public class WeixinUser implements Observer {
// Wechat account name
private String name;
public WeixinUser(String name) {
this.name = name;
}
@Override
public void update(String message) {
System.out.println(name + "-"+ message); }}Copy the code
Define abstract topic class, provide attach, detach, notify three methods
public interface Subject {
// Add subscribers
public void attach(Observer observer);
// Delete the subscriber
public void detach(Observer observer);
// Notify subscribers of updates
public void notify(String message);
}
Copy the code
Wechat public account is a specific theme (specific observed), which stores the wechat users who subscribe to the public account, and implements the method in the abstract theme
public class SubscriptionSubject implements Subject {
// Store wechat users who subscribe to public accounts
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); }}}Copy the code
Client program
public class Client {
public static void main(String[] args) {
SubscriptionSubject mSubscriptionSubject=new SubscriptionSubject();
// Create a wechat user
WeixinUser user1=new WeixinUser("Sun Wukong");
WeixinUser user2=new WeixinUser("Pig Wuneng");
WeixinUser user3=new WeixinUser("Sha Wu Jing");
// Subscribe to the public account
mSubscriptionSubject.attach(user1);
mSubscriptionSubject.attach(user2);
mSubscriptionSubject.attach(user3);
// Public account updates send messages to subscribed wechat users
mSubscriptionSubject.notify("The dark Horse column has been updated."); }}Copy the code
The advantages and disadvantages
1. Advantages:
- The coupling relationship between the target and the observer is abstract.
- The observed sends a notification, all registered observers will receive the message [can implement broadcast mechanism]
2. Disadvantages:
- If there are too many observers, it will take time for all observers to receive the notification sent by the observer
- If the observed has a loop dependency, then the observed sends a notification which causes the observer to loop, causing the system to crash
Usage scenarios
- Objects have a one-to-many relationship. Changes in the state of one object affect other objects.
- When an abstract model has two aspects, one of which depends on the other.
Implementation provided in the JDK
In Java, the Observer pattern is defined through the java.util.Observable class and the java.util.Observer interface, and instances of the Observer pattern can be written by implementing their subclasses.
Class 1, observables
An Observable is an abstract object class. It has a Vector member variable that holds all Observable objects to be notified. Here are three of its 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 for all observer objects in the collection, notifying them of data changes. Observers who join the collection later are usually notified first.
-
The void setChange() method: Sets an internal Boolean flag indicating that the target object has changed. When it is true, notifyObservers() notifyObservers.
2, Observer interface
The Observer interface is an abstract Observer that monitors changes in the target object, notifies the Observer when the target object changes, and calls the Update method to do the work accordingly.
The police caught the thief
Police catching thieves can also be implemented using the observer model, where the police are the observers and the thief is the observed. The code is as follows:
The thief is an Observable, so it 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(a) {
return name;
}
public void steal(a) {
System.out.println("Thief: I stole something, have someone to catch me!!");
super.setChanged(); //changed = true
super.notifyObservers(); }}Copy the code
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(a) {
return name;
}
@Override
public void update(Observable o, Object arg) {
System.out.println("Policeman:" + ((Thief) o).getName() + ", I have been watching you for a long time, you can keep silent, but anything you say can and will be used against you in a court of law!!"); }}Copy the code
Client code
public class Client {
public static void main(String[] args) {
// Create thief object
Thief t = new Thief("Next door Lao Wang");
// Create a police object
Policemen p = new Policemen("Xiao li");
// Keep the police on the thief
t.addObserver(p);
// Thieves steal thingst.steal(); }}Copy the code