Android Design Patterns - Observer Patterns

Posted by killswitchfilter on Mon, 09 Sep 2019 14:43:54 +0200

For loading, please indicate the source: https://www.cnblogs.com/tangZH/p/11175120.html 

 

Observer model

To put it bluntly, it is a one-to-many relationship that changes everything that depends on it.

For example, object A, object B, object C. B and C depend on A, so A will change, B and C will also change. At this time A is the observer, B and C are the observer.

 

The observer model, also known as the publish/subscribe model, is designed to decouple the observer from the observee.

 

UML diagram:

 

 

Role description:

Subject: An abstract class of the observee that stores all observer references in a collection. Abstract topics provide an interface to add and delete observer objects.

ConcreteSubject: Specific observer. Every registered observer is notified when the state of the specific observee changes.

Observer (abstract observer): An abstract class of all concrete observers that defines an interface for all concrete observers: update yourself when notified of the subject.

ConcrereObserver: A concrete implementation of an abstract observer.

 

Let's look at a specific example:

Teachers and students reacted differently when the bell rang.

1. Define an abstract topic:

This abstract topic defines some general methods that need to be implemented within a specific topic.

//Abstract observee
public interface Observable {
    //Adding observers
    void addObserver(Observer observer);

    //Remove the observer
    void deleteObserver(Observer observer);

    //Notify the observer
    void notifyObserver(String msg);
}

 

2. Create a specific theme (class bell):

public class AlarmClock implements Observable {
    //Preserving the Observer Object
    List<Observer> list = new ArrayList<>();

    @Override
    public void addObserver(Observer observer) {
        list.add(observer);
    }

    @Override
    public void deleteObserver(Observer observer) {
        list.remove(observer);
    }

    /**
     * Notify the observer
     * @param msg
     */
    @Override
    public void notifyObserver(String msg) {
        for (Observer observer : list) {
            observer.action(msg);
        }
    }
}

 

3. Create Abstract observers:

Define the methods that all specific observers need to implement and the behavior after hearing the bell

//Abstract observer
public interface Observer {
    void action(String msg);
}

 

4. Create specific observers:

public class Students implements Observer {

    String name;

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

    @Override
    public void action(String msg) {
        System.out.println(msg + name + "Start attending classes");
    }
}
public class Teacher implements Observer {
    @Override
    public void action(String msg) {
        System.out.print(msg + "The teacher began his lecture.");
    }
}

 

6. Realize:

Observable alarmClock = new AlarmClock();

Observer student1 = new Students("A baby boy");
Observer student2 = new Students("Big-ass kid");
Observer teacher = new Teacher();

//Registered observer
alarmClock.addObserver(student1);
alarmClock.addObserver(student2);
alarmClock.addObserver(teacher);

//Observed notifies registered observers
alarmClock.notifyObserver("The bell has rang for class.");

 

7. Result:

 

Here we have realized the observer model.

 

Application scenarios

  • When an object's change needs to be notified to other objects, and it does not know how many objects need to be changed.
  • When an object must notify other objects, it cannot assume who the other objects are.
  • Cross-system message exchange scenarios, such as message queues, event bus processing mechanisms.

Advantage

  • Decoupling the observer from the subject. Let both sides of the coupling depend on abstraction rather than on concrete. So that each change will not affect the other side of the change.
  • Easy to expand, no need to modify the original code when adding observers to the same topic.

Disadvantages

  • Dependency has not been completely relieved, and abstract topics still rely on abstract observers.
  • When using the observer mode, we need to consider the development efficiency and operation efficiency. The program includes an observer, multiple observers, development, debugging and other content will be more complex. Moreover, in Java, message notification is usually executed sequentially, so an observer Katon will affect the overall execution efficiency. In this case, asynchronous implementation is usually used.
  • It may cause redundant data notifications.

JDK also has built-in Observable (abstract observer), Observer (abstract observer) these two classes, we can also use them directly, specifically to see the source code.
 
Observer mode is also used in many places in Android:
  • Click Events
  • listView refresh
  • Broadcasting and so on

Topics: Android Java JDK