1. Preliminary understanding

Definition of observer mode:

One-to-many dependencies are defined between objects so that when an object changes state, dependent objects are notified and updated automatically.

Opacity:

In fact, it is a publish and subscribe model, publishers publish information, subscribers get information, subscribe can receive information, do not subscribe to receive information.

2. Structure diagram of this pattern

3. As you can see, this pattern contains four roles

  • Abstract Observed role: That is, an abstract topic that stores all references to observer objects in a collection, and each topic can have any number of observers. Abstract themes provide an interface to add and remove observer roles. It is typically implemented with an abstract class and interface.

  • Abstract observer roles: Define an interface for all concrete observers to update themselves when notified of a topic.

  • Specific observed role: that is, for a specific subject, all registered observers are notified when the internal state of the collective subject changes.

  • Concrete observer role: The update interface needed to implement the abstract observer role while reconciling its own state with the state of the drawing.

4. Use scenario examples

There is a wechat public account service that releases some messages from time to time. If you follow the account, you can receive push messages. If you cancel the account, you cannot receive push messages.

5. Concrete implementation of observer mode

1. Define an abstract observed interface

package com.jstao.observer; * @author jstao ** / public interface Observerable {public void registerObserver(Observer o); public void removeObserver(Observer o); public void notifyObserver(); }Copy the code

Define an abstract observer interface

package com.jstao.observer; /*** * Abstract observers * defines an update() method, which is called back when observers call notifyObservers(). * @author jstao * */ public interface Observer { public void update(String message); }Copy the code

3, the Observerable interface is defined, and the Observerable interface is implemented in three ways. At the same time, there is a List set to save the registered observer. When the observer needs to be notified, the set can be traversed.

package com.jstao.observer; import java.util.ArrayList; import java.util.List; /** * The Observerable interface is implemented. * @author jstao * */ public class WechatServer implements Observerable { Private List<Observer> List; private List<Observer> List; private String message; publicWechatServer() {
        list = new ArrayList<Observer>();
    }
    
    @Override
    public void registerObserver(Observer o) {
        
        list.add(o);
    }
    
    @Override
    public void removeObserver(Observer o) {
        if(! list.isEmpty()) list.remove(o); } // Override public voidnotifyObserver() {
        for(int i = 0; i < list.size(); i++) {
            Observer oserver = list.get(i);
            oserver.update(message);
        }
    }
    
    public void setInfomation(String s) {
        this.message = s;
        System.out.println("Wechat Service Update message:"+ s); NotifyObserver (); // notifyObserver(); }}Copy the code

4. Define specific observer. The specific observer of wechat public account is User

package com.jstao.observer; @author jstao ** / public class User implements Observer {private String name; private String message; public User(String name) { this.name = name; } @Override public void update(String message) { this.message = message;read(a); } public voidread() {
        System.out.println(name + "Received push message:"+ message); }}Copy the code

Write a test class

First, I registered three users, ZhangSan, LiSi and WangWu. The public account posted a message saying “PHP is the best language in the world!” All three users received the message.

After ZhangSan saw the message, he was quite shocked and cancelled his subscription. At this time, the public account pushed another message. At this time, ZhangSan had not received the message, and other users

Still can receive push message normally.

package com.jstao.observer;

public class Test {
    
    public static void main(String[] args) {
        WechatServer server = new WechatServer();
        
        Observer userZhang = new User("ZhangSan");
        Observer userLi = new User("LiSi");
        Observer userWang = new User("WangWu");
        
        server.registerObserver(userZhang);
        server.registerObserver(userLi);
        server.registerObserver(userWang);
        server.setInfomation("PHP is the best language in the world!");
        
        System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -");
        server.removeObserver(userZhang);
        server.setInfomation("JAVA is the best language in the world!"); }}Copy the code

Test results:

  • This pattern is loosely coupled. Change one side of the subject or observer, the other side does not receive the image.

  • The JDK also has a built-in observer mode. However, being observed is a class rather than an interface, which limits its reuse capability.

  • The observer pattern can also be seen in Javabeans and Swing.

Note: If you are the fireworks on the sea, I am the foam on the waves.