Android design mode - observer mode - behavioral-

Posted by mighty on Sun, 23 Jan 2022 09:50:28 +0100

  • Android design pattern Github project address: Click jump

0. What is observer mode?

When there is a corresponding dependency relationship between objects, so that when the state of the dependent object changes, all objects that depend on it can be notified and react.
When objects A and B are registered with object C. AB is the dependent object and C is the dependent object.
Dependent object: we call it Observable
Dependent object: we call it Observer

Characteristics to be observed:
1. Container - for example, an ArrayList collection class, which is used to save all registered observers
2. Customize abstract classes and provide methods for registering and deleting containers
3. Customize the abstract class and provide methods to update (notify) all observers in the container

Characteristics required by the observer:
1. Customize the abstract class and implement its methods (the methods to be done after receiving the update notification from the observed object)
2. Register yourself with the observed object

1. Advantages and disadvantages

advantage:

The observer and the observed are abstractly coupled. 2. Establish a trigger mechanism.

Disadvantages:

If an observed object has many direct and indirect observers, it will take a lot of time to notify all observers. 2. If there is a circular dependency between the observer and the observation target, the observation target will trigger a circular call between them, which may lead to system crash. 3. The observer model has no corresponding mechanism to let the observer know how the observed target object has changed, but only know that the observed target has changed.

Usage scenario:

An abstract model has two aspects, one of which depends on the other. These aspects are encapsulated in independent objects so that they can be changed and reused independently.
.
The change of one object will lead to the change of one or more other objects, and the coupling between objects can be reduced by not knowing how many objects will change.
.
An object must notify other objects without knowing who they are.
You need to create A trigger chain in the system. The behavior of object A will affect object B, and the behavior of object B will affect object C.. You can use the observer mode to create A chain trigger mechanism.

matters needing attention:

1. JAVA already has support classes for the observer pattern.
2. Avoid circular references.
3. If the sequence is executed, an observer error will cause the system to jam, and the asynchronous mode is generally adopted.

2. Which libraries or methods are implemented using observer mode?

Listener, click event, scroll event
rxjava, eventbus, broadcast architecture component Livedata

3. Examples - Students - Teachers

Participants: Teachers (observed), ordinary students, monitor (observer)
Event: the teacher went to the meeting and all the students in the class were informed. Ordinary students and monitor responded differently

  • 1. Students define abstract methods
/**
 * Create an abstract observer and define the notification received
 * Observer
 */
public interface StudentObserverInterface {
    void receivedNotifyFromTeacher(String msg);
}
  • 2. Student class implements user-defined abstract methods
/**
 * Create concrete observers, implement abstract methods, and respond to notifications received
 * Concrete
 */
public class StudentObserver implements StudentObserverInterface {
    private String studentName; //Student name
    private boolean isMonitor; //Is he the monitor

    public StudentObserver (String studentName,boolean isMonitor){
        this.studentName = studentName;
        this.isMonitor = isMonitor;
    }
    @Override
    public void receivedNotifyFromTeacher(String msg) {
        if(isMonitor){ //If it's the monitor
            Log.d(ObserverPatternActivity.TAG, studentName+":>> Good teacher! I will maintain class order");
        }else {  //Ordinary students
            Log.d(ObserverPatternActivity.TAG, studentName+":>> Great. The teacher went to the meeting");
        }
    }
}
  • 3. Teacher defined abstract methods (registration, addition, deletion, update)
/**
 * Create abstract (observed) topics and define methods such as adding, deleting and notifying:
 * Subject
 */
public interface TeacherObservableInterface {
    void addStudent(StudentObserverInterface observer);//Add observer (add student)

    void removeStudent(StudentObserverInterface observer);//Delete observer (delete student)

    void notifyToStudent(String message);//Notify observer (notify student)
}
  • 4. The teacher class implements user-defined abstract methods
/**
 * Create concrete (observed) topics and implement abstract methods.
 * ConcreteSubject
 */
public class TeacherObservable implements TeacherObservableInterface {
    //Container container
    private ArrayList<StudentObserverInterface> studentList = new ArrayList<StudentObserverInterface>();//Save recipient (observer) information

    @Override
    public void addStudent(StudentObserverInterface observer) {
        studentList.add(observer);
    }

    @Override
    public void removeStudent(StudentObserverInterface observer) {
        studentList.remove(observer);
    }

    @Override
    public void notifyToStudent(String message) {
        for(int i = 0; i< studentList.size(); i++){ //Notify all observers one by one (this refers to notifying all students one by one)
            studentList.get(i).receivedNotifyFromTeacher(message);
        }
    }
    public ArrayList<StudentObserverInterface> getStudentList(){
        return studentList;
    }
}
  • 5.activity
public class ObserverPatternActivity extends AppCompatActivity {
    private TeacherObservable mTeacherObservable = new TeacherObservable();
    public static String TAG ="Observer mode:>> ";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_observer_pattern);
        addStudent();
        teacherNotify();
    }

    private void addStudent(){
        StudentObserver studentObserver1 = new StudentObserver("Xiao Hong",true);
        mTeacherObservable.addStudent(studentObserver1);
        StudentObserver studentObserver2 = new StudentObserver("Li Ming",false);
        mTeacherObservable.addStudent(studentObserver2);
        StudentObserver studentObserver3 = new StudentObserver("Zhang San",false);
        mTeacherObservable.addStudent(studentObserver3);
    }
    private void teacherNotify(){
        Log.d(TAG, "The teacher held a meeting and issued a notice to all students: ");
        mTeacherObservable.notifyToStudent("The teacher went to the meeting,The monitor is in charge of the class");
    }

}

The result after running is:

If Zhang San drops out of school, we need to delete Zhang San from the teacher's container, so that Zhang San will not receive the notification event.

public class ObserverPatternActivity extends AppCompatActivity {
    private TeacherObservable mTeacherObservable = new TeacherObservable();
    public static String TAG ="Observer mode:>> ";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_observer_pattern);
        addStudent();
        removeStudent();
        teacherNotify();
    }

    private void addStudent(){
        StudentObserver studentObserver1 = new StudentObserver("Xiao Hong",true);
        mTeacherObservable.addStudent(studentObserver1);
        StudentObserver studentObserver2 = new StudentObserver("Li Ming",false);
        mTeacherObservable.addStudent(studentObserver2);
        StudentObserver studentObserver3 = new StudentObserver("Zhang San",false);
        mTeacherObservable.addStudent(studentObserver3);
    }
    private void teacherNotify(){
        Log.d(TAG, "The teacher held a meeting and issued a notice to all students: ");
        mTeacherObservable.notifyToStudent("The teacher went to the meeting,The monitor is in charge of the class");
    }
    private void removeStudent(){
        mTeacherObservable.removeStudent(mTeacherObservable.getStudentList().get(0));
    }
}

The result after running is:

4. Android technology life exchange

WeChat


[1]* Reference article 1
[2]* Reference article 2
[3]* Reference article 3
[4]* Reference article 4
[5]* Reference article 5