introduce

The observer pattern is a highly used pattern, most commonly used in GUI systems, subscription-publish, because one of the important functions of this pattern is decoupling, decoupling the observer from the observer, making them less dependent on each other, or even no dependency at all. In the case of GUI system, the UI of application is changeable. Especially in the early stage, with the change of business or product demand, the application interface will change frequently, but the business logic basically does not change. At this time, GUI system needs a set of mechanism to cope with this situation, so that the UI layer is decoupled from the specific business logic. This is where observer mode comes in handy.

define

Define a 1-to-n relationship between objects such that whenever an object changes state, all dependent objects are notified and automatically updated.

Usage scenarios

  1. Associative behavior scenarios, it is important to note that associative behavior is separable, not “combined” relationships.
  2. Multi-level event triggering scenario.
  3. Message exchange scenarios across systems, such as message queues, message mechanisms for event buses.

UML class diagrams

  • Subject: Abstract Subject, that is, the role of the observed, the abstract Subject role of all observers

    Object references are kept in a collection, each topic can have any number of observers, and abstract topics provide an interface to add and remove observer objects.

  • ConcreteSubject: Concrete topic. This role stores the state in a concrete observer object and notifies all registered observers when the internal state of a concrete topic changes. ConcreteSubject is called concreteobserved.

  • Observer: Abstract Observer, which implements the update interface defined by the abstract Observer role to update its own state when the state of a topic changes.

In actual combat

Requirements: subscribe to a website technical article, update push.

Define an observer object – user

public class Coder implements Observer {
    private String name;

    public Coder(String name) {
        this.name = name;
    }


    /** * will execute * if there are updates@param o
     * @param arg
     */
    @Override
    public void update(Observable o, Object arg) {
        System.out.println("o = [" + o + "], arg = [" + name + "" + (String) arg + "]");

    }

    @Override
    public String toString(a) {
        return "Coder{" +
                "name='" + name + '\' ' +
                '} '; }}Copy the code

Define the observed object – technical site

public class JueJ extends Observable {
    /** * push *@param content
     */
    public void post(String content){
        // Indicates that the state or content needs to change
        setChanged();
        // Notify all subscribersnotifyObservers(content); }}Copy the code

Testing:

    @Test
    public void testObserver(a){
        // Create the observed -- technical website
        JueJ jueJ = new JueJ();

        // Create an observer
        Coder coderA = new Coder("A");
        Coder coderB = new Coder("B");
        Coder coderC = new Coder("C");

        // Create a subscription, add to the list of observed, and push updates to them
        jueJ.addObserver(coderA);
        jueJ.addObserver(coderB);
        jueJ.addObserver(coderC);

        // There is an update, notify observers
        jueJ.post("Dev_YK: Updated a design pattern article, click to view it." );
    }

Copy the code

Output:

o = [com.devyk.android_dp_code.observer.JueJ@48533e64], arg = [C Dev_YK: Updated a design pattern article, click to view it.]  o = [com.devyk.android_dp_code.observer.JueJ@48533e64], arg = [B Dev_YK: Updated a design pattern article, click to view it.]  o = [com.devyk.android_dp_code.observer.JueJ@48533e64], arg = [A Dev_YK: Updated A design pattern article, click to view it.]Copy the code

You can see that all users who subscribe to a technology site are notified of updates, and the one-to-many subscription-publish system is complete.

conclusion

The main function of the observer mode is decoupling, completely isolating the observer from the observed and relying only on the Observe and Observable abstractions.

Advantages:

  • The observer and observed are abstractly coupled in response to business changes.
  • Enhance system flexibility and expansibility.

Disadvantages:

  • Need to consider the development efficiency when using the observer pattern and efficiency problem, the program includes a observed, more than one observer, development and debugging, etc will be more complex, and the notice of default is in Java message order, an observer caton, will affect the overall execution efficiency, and in this case, generally consider using asynchronous mode.

Article code address

Special thanks to

Android source code design pattern analysis and combat

Thank you for reading, thank you!