One Day Pattern - Observer Mode

1. The concept of observer mode

The observer mode, also known as the Publish/Subscribe mode, is one of the behavioral modes that defines a one-to-many dependency that allows multiple observer objects to listen on a topic at the same time.When the state of the subject object changes, all observer objects are notified so that they can update themselves automatically.

2. When to use the observer mode

The observer mode can be used when an object is modified or changes to something that automatically notifies some of the objects that depend on it.

For example, when a car goes out, you need to update its positioning, send a notification of the car going out, and generate this trip. You can use the observer mode. In this example, the location where the change happens is going out, so some of the objects that depend on it need to be notified of the happening of the car going out are positioning, notification and travel.

Here's how to implement the observer mode in Java.

3. How to use the observer mode

3.1 Disadvantages of Not Applying Observer Mode

Using the business scenario described above as an example, if you don't implement it using the observer mode, you can see the following pseudocode:

public class EngineOffEvent() {

    public void engineOff() {
        Location localtion = new Localtion();
        Notification notification = new Notification();
        Trip trip = new Trip();

        localtion.update();
        notification.notify();
        trip.createTrip();
    }
}

This approach has two main drawbacks:

  • High coupling: You can see that the EngineOffEvent class couples all other business classes, making maintenance difficult;
  • Poor scalability: When new business needs to be done when the fire goes off, the code in the engineOff method needs to be modified, which violates the open-close principle;
  • Low flexibility: cannot control the number of objects to be notified;

3.2 How to Solve Problems Using the Observer Mode

Based on the above requirements, design in observer mode, and look at the class diagram and code below:

The code is as follows:

/**
 * Observer interface.
 * */
public interface Observer {
    /**
     * When meteorological monitoring data changes, the subject transmits these state values to the observer as parameters of the method.
     * */
    void update(String data);
}

public class LocaltionObserver implements Observer{
    public void update(String data) {
        System.out.println(data + ": Update location.");
    }
}

public class NotificationObserver implements Observer{
    public void update(String data) {
        System.out.println(data + ": Send notifications.");
    }
}

public class TripObserver implements Observer {
    public void update(String data) {
        System.out.println(data + ": Generate trip.");
    }
}

/**
 * Theme interface.
 * */
public interface Subject {
    /**
     * registerObserver Both the removeObserver method and the removeObserver method require an observer as a variable that is registered or deleted.
     * */
    void registerObserver(Observer ob);

    void removeObserver(Observer ob);

    /**
     * When the state of the subject changes, this method is called and all observers are notified.
     * */
    void notifyObservers(String data);

}

// Flame extinction event
public class EngineOffEvent implements Subject {

    // A collection of observer objects
    private List<Observer> observers;

    public EngineOffEvent() {
        observers = new ArrayList<Observer>();
    }

    // Register Observers
    public void registerObserver(Observer ob) {
        observers.add(ob);
    }

    // Remove Observer
    public void removeObserver(Observer ob) {
        int index = observers.indexOf(ob);
        if (index >= 0)
            observers.remove(index);
    }

    // Notify of changes
    public void notifyObservers(String data) {
        // Notify all observers
        for (Observer ob : observers) {
            ob.update(data);
        }
    }

}

// Use
public class Client {

    public static void main(String[] args) {
        Subject subject = new EngineOffEvent();
        subject.registerObserver(new LocaltionObserver());
        subject.registerObserver(new NotificationObserver());
        subject.registerObserver(new TripObserver());
        subject.notifyObservers("Beijing A88888 Extinguish fire");
    }

}

//Beijing A88888 goes out: update location.
//Beijing A88888 goes out: send notification.
//Beijing A88888 Fire Extinguishing: Generating trip.

The observer model is divided into two main parts:

  • Subject, Subject, is the object that changed, in example, the fire extinguishing event;
  • Observer, an observer, is a number of objects that need to be notified of changes, such as notifications, locations, and processes.

During use, observers can be dynamically added or deleted to provide flexible configuration.

3.3 Benefits of the observer model

  • Low coupling: The EngineOffEvent class is decoupled from other business classes in section 3.1;
  • Extensibility: When you need to do new business when the fire goes off, create a new object to implement Observer and register it with Subject.
  • High flexibility: Observer can be added or removed at will;

3.4 Other things to note

Java has built-in observer mode:

  • java.util.Observable(Class)

  • java.util.Observer(interface)

You can use a built-in observer, but Observable corresponds to the Subject in the example above. He is a Class, not an Interface. If you use a built-in interface, you need to use up valuable inheritance opportunities. If your class already uses an inheritance relationship, you cannot.

4. Summary

The observer mode above, which is coded as polygon interface programming, has a List <Observer> in Subject that, after a change, loops through the methods of the objects in the List to ensure that they are notified and that lists can be added and deleted.

Business-wise, when an event occurs, many objects need to be notified in bulk.You can use this mode.

These are just some of my understandings of the observer model. There are some deficiencies. Please point out that thank you.

Tags: Programming Java

Posted on Tue, 26 May 2020 13:10:46 -0400 by Tristan Wells