What is the subscription publishing model

The subscription publishing pattern defines a one-to-many dependency relationship. One refers to the publisher, such as a topic object, and more refers to the subscriber. The dependency is the subscriber’s dependence on the publisher. Multiple subscribers listen on a topic object simultaneously. When the state of the publisher, the topic object, changes, the subscriber is notified of the change, and the subscriber updates his state accordingly. It’s one of the more commonly used design patterns.

Second, why use subscription publishing model

The subscription publishing pattern is designed to reduce coupling between different modules of the system. A complex system is generally divided into many different classes, which are not independent and have various cooperative relationships. This requires the maintenance of consistency between objects, which brings inconvenience to the maintenance, reuse and expansion of the system and seriously limits the flexibility of the system. In this way, active variables can be abstracted as publishers, while other dependencies can be abstracted as subscribers, allowing them to be reused and maintained independently. Both rely only on abstraction, not implementation. For example, when a publisher adds a subscriber, it only needs to register with the publisher. When a subscriber adds a dependency, it only needs to register with the new publisher.

Three, an example:

There is a weather forecast system that tells us what the weather will be like tomorrow. Several roles subscribe to the system, and they schedule tomorrow’s events based on the weather. They are farmers, construction workers, and programmers.

When it rains, the farmer is overjoyed: he can have a good rest for another day and let his crops grow well. The construction worker is overjoyed: perfect, sleeping through the night; Programmer: continue to work, close my hair matter;

Sunny thousands of miles farmer feeling: will meet a full day, harvest full; Construction workers complain: such a big sun, but painful day; Programmer: continue to work, close my hair matter;

Specific implementation process using Java language:

1. Publisher Interface:

Public interface IWeather {void addSubscriber(ISubscriber subscriber); public interface IWeather {void addSubscriber(ISubscriber subscriber); void delSubscriber(ISubscriber subscriber); void publishInfo(String msg); }Copy the code

2. Publisher concrete implementation

import org.apache.log4j.Logger; import java.util.ArrayList; import java.util.List; /* Public class WeatherServer implements IWeather {private static final Logger Logger = Logger.getLogger(WeatherServer.class); */ Private List<ISubscriber> Subscribers = new ArrayList<ISubscriber>(); public void addSubscriber(ISubscriber subscriber) { subscribers.add(subscriber); logger.info("a new subscriber is joining");
    }

    public void delSubscriber(ISubscriber subscriber) {
        subscribers.remove(subscriber);
        logger.info("a subscriber is leaving");
    }

    public void publishInfo(String msg) {
        for(ISubscriber subscriber : subscribers) subscriber.todoTomorrow(msg);
        logger.info(String.format("publish a msg: %s ",msg)); }}Copy the code

Subscriber interface

Public interface ISubscriber {void todoTomorrow(String) public interface ISubscriber {void todoTomorrow(String) msg); }Copy the code

4. Realization of specific subscribers

import org.apache.log4j.Logger;
public class Farmer implements ISubscriber{
    private static final Logger logger = Logger.getLogger(Farmer.class);

    public void todoTomorrow(String msg) {

        if("rain".equals(msg)){
            logger.info("FARMER : a wonderful day!!!");
        }else if("sunny".equals(msg)){
            logger.info("FARMER : a enrich day!!!");
        }else {
            logger.info("FARMER : Spam messages");
        }
    }
}


public class Worker implements ISubscriber{
    private static final Logger logger = Logger.getLogger(Farmer.class);

    public void todoTomorrow(String msg) {

        if("rain".equals(msg)){
            logger.info("WORKER : a satisfied day!!!");
        }else if("sunny".equals(msg)){
            logger.info("WORKER : a terrible day!!!");
        }else {
            logger.info("WORKER : Spam messages");
        }
    }
}


public class Programmer implements ISubscriber{
    private static final Logger logger = Logger.getLogger(Farmer.class);

    public void todoTomorrow(String msg) {

        if("rain".equals(msg)){
            logger.info("PROGRAMMER :raining??? Irrelevant !!!");
        }else if("sunny".equals(msg)){
            logger.info("PROGRAMMER : sunny Irrelevant !!!");
        }else {
            logger.info("PROGRAMMER : Spam messages"); }}}Copy the code

5. The test class

 */
public class Boot {


    public static void main(String[] args){

        Farmer farmer = new Farmer();
        Worker worker = new Worker();
        Programmer programmer = new Programmer();

        WeatherServer weatherServer = new WeatherServer();

        weatherServer.addSubscriber(farmer);
        weatherServer.addSubscriber(worker);
        weatherServer.addSubscriber(programmer);

        weatherServer.publishInfo("rain"); }}Copy the code

6. Operation results:

When a new subscriber wants to subscribe to the weather forecast service, it only needs to call the addSubscriber registration method of weather to complete the registration and receive the weather forecast information.