define

Define a one-to-many dependency between objects so that every time an object changes state, all registered observers are notified and updated automatically

For example: Nuggets is a technical forum, everyone follows me, then I post an article, all the people following me can receive my update article prompt, this is a simple observer example, see the code below implementation

UML class diagrams

  • Subject: The role of the observed
  • JuejinSubject (Concrete Subject) : Is a class that inherits an abstract subject, registers, unregisters, and handles observer changes
  • Observe: An observer is an interface to the water bank of an object, updated according to changes in the topic.
  • Coder (Concrete Observer): This role implements the update interface defined by the abstract observer role to update the generated state when the topic state changes

Code implementation

SubJect abstracts a topic by registering, unregistering, and notifying subscribers

public abstract class SubJect {
    // Register for a subscription
    void registerObserver(Observer observer) {}// Unregister the subscription
    void unRegisterObserver(Observer observer){}
     // Notify subscribers
    void notifyObserver(String message){}}Copy the code

JuejinSubject Concrete topic class that implements methods for abstract topics

public class JuejinSubject extends SubJect {
    private List<Observer> observerList = new ArrayList<>();  // Subscriber container, Observer

    @Override
    public void registerObserver(Observer observer) {
        if(! observerList.contains(observer)) { observerList.add(observer);// Add a subscription}}@Override
    public void unRegisterObserver(Observer observer) {
        if (observerList.contains(observer)) {
            observerList.remove(observer);  // Remove the subscription}}@Override
    public void notifyObserver(String message) {
        for (Observer observer :
                observerList) {
            observer.notify(message);  / / notice}}}Copy the code

Observer Abstracts the Observer and defines an update interface

public interface Observer {
    void notify(String message);
}
Copy the code

Coder specific observer

class Coder implements Observer {
    private String name;
    public Coder(String name){
        this.name = name;
    }
    @Override
    public void notify(String message) {
        System.out.println("hi " +name +"The juejin theme you subscribed to has been updated, updated content"+ message); }}Copy the code

Test Indicates the code of the Test class

public class Test {
    public static void main(String[] args) {
        JuejinSubject juejinSubject = new JuejinSubject(); // Dig gold for the observed object

        // Programmer observer
        Coder coderA = new Coder("Programmer A");
        Coder coderB = new Coder("Programmer B");
        Coder coderC = new Coder("Programmer C");
        Coder coderD = new Coder("Programmer D");

        // Register for observation
        juejinSubject.registerObserver(coderA);
        juejinSubject.registerObserver(coderB);
        juejinSubject.registerObserver(coderC);
        juejinSubject.registerObserver(coderD);

        // Notify the observer
        juejinSubject.notifyObserver("Ding Da published a new article, please check it out >_>"); }}Copy the code

Output:

The well-known Android library EventBus is an example of the completed observer pattern. I have time to analyze it for you.

conclusion

The Observer mode plays an important role in object coupling, completely coupling the Observer with the observed, relying only on the Observer and Observable abstractions. Rational use of design pattern can make the code structure more clear, but also to meet the different small modules in line with the single responsibility, and the principle of open and closed, so as to achieve the factory pattern described in the previous, improve the scalability of the code, low maintenance costs.

advantages
  • The observer and observed are abstractly coupled in response to business changes
  • Enhance system flexibility and scalability
disadvantages
  • The application of observer mode needs to consider the problems of development efficiency and operation efficiency. The program includes one observer and multiple observers, and the amount of code will be more, and the development and testing will be more complicated.

That’s all for observer mode, give it a thumbs up if you like.