Java Design Pattern – Observer pattern (Subscribe publish pattern)
Will be a review ya, will not come to see it together.
Like a sentence: “eight hours for life, eight hours for development”.
If you like it, let’s stick to it!!
‘😁
Hello, I like you
Design Mode series:
- Java Design pattern – singleton pattern
- Java Design Pattern – Factory Pattern (1) Simple Factory pattern
- Java Design Pattern – Factory Pattern (2) Factory method pattern
- Java Design Pattern – Factory Pattern (3) Abstract Factory pattern
- Java Design pattern – Builder pattern
- Java Design pattern – Proxy pattern
- Java Design pattern – Adapter pattern
- Java Design pattern – Decorator pattern
- Java Design pattern – Bridge pattern
- Java Design pattern – Appearance pattern
- Java Design pattern – Composite pattern
- Java Design pattern – Share meta pattern
- Java Design Pattern – Template method pattern
- Java Design pattern – Policy pattern
- Java Design pattern – Chain of Responsibility pattern
- Java Design Pattern – The Mediator pattern
- Java Design Pattern – Observer Pattern (publish/subscribe pattern)
- Continuously updated…
One, foreword
1) Introduction:
In the real world, many objects do not exist independently, and a change in the behavior of one object may lead to a change in the behavior of one or more other objects.
For example, stock prices and shareholders, wechat public accounts and wechat users, weather forecasts and listeners of the Meteorological Bureau, etc. And the bell rings. It’s time to go into the classroom.
The same is true in the software world, for example, of the relationship between data in Excel and line charts, pie charts, and bar charts; The relationship between model and view in MVC pattern; Event sources and event handlers in the event model. All of this is very handy if you use the observer pattern.
2) Overview:
The Observer pattern is defined as a one-to-many dependency between multiple objects. When an object’s state changes, all dependent objects are notified and automatically updated. This pattern, sometimes referred to as publish-subscribe or model-view, is an object behavior pattern.
3) Role Structure:
- 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.
4) Precautions:
1. Avoid circular references. 2. If executed sequentially, an observer error will cause the system to jam, usually asynchronously.
Ii. Case code
2.1 Cases:
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 XXX.
The class diagram
2.2. Implementation:
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("Xiao Ming");
WeixinUser user2=new WeixinUser("Wang");
WeixinUser user3=new WeixinUser("Xiao li");
// 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("Ning zaichun's article is updated!!");
/** * Xiao Ming - ning zaichun's article is updated!! * Xiao Wang - ning in spring's article updated!! * Xiaoli-Ning's article is updated!! * /}}Copy the code
A message sent by a wechat official account can be received by all subscribers.
I previously wrote about SpringBoot’s integration with Redis for a publish/subscribe model. Everyone interested can have a look ha!!
Third, summary
Advantages:
- The coupling relationship between the target and the observer is abstract. In line with the principle of dependency inversion.
- A set of triggers is established between the target and the observer.
Disadvantages:
1. If there are 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. (i.e. no confirmation mechanism)
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, the two can be encapsulated in separate objects so that they can be changed and reused independently.
- To realize functions similar to the broadcast mechanism, it is not necessary to know the specific receiver, but only to distribute the broadcast, and the interested objects in the system will automatically receive the broadcast.
- Multiple levels of nesting are used to form a chain trigger mechanism that allows events to be notified across domains (across both observer types)
4. Talk to yourself
I do not know whether the article is useful or useless, just want to do a share. I hope you can enjoy it and have a good harvest here.
Of course, THERE is no denying that I also want to achieve the kind of happiness of other people’s approval, and I can continue to maintain it.
Hello, be happy every day. See you in the next article.
This series is still being updated…. I’ll be back for sure. 😁
In a group full of big guy saw this chart 😂, we are the new generation of migrant workers!!
However, labor is the most glorious, as I will become a new generation of migrant workers, I want to continue to roll. Ha 😁
I hope that when we meet on another day, we will have achieved something.