Q: What are design patterns

Slowly: Design pattern is a solution for common scenarios in system service design, which can solve common problems encountered in the development of functional logic. Design pattern is not limited to the final implementation scheme, but in this conceptual pattern, to solve the code logic problems in system design.

Q: What is observer mode?

Slowly: When objects have one-to-many dependencies, the observer mode allows all dependent objects to be notified and updated when an object’s state changes.

Q: Let’s get on the code.

Abstract observer

public interface Observer {
    void response(a);  / / response
}
Copy the code

Specific observer 1

public Observer1 implements Observer {
    public void response(a) {
        System.out.println("Specific observer 1 reacts.")}}Copy the code

Specific observer 2

public Observer2 implements Observer {
    public void response(a) {
        System.out.println("Specific observer 2 responds.")}}Copy the code

Abstract objective

public abstract class Subject {
    protected List<Observer> observers = new ArrayList<>();
  
    // Add an observer
    public void add(Observer observer) {
        observers.add(observer);
    }
  
    // Delete the observer
    public void remove(Observer observer) {
        observers.remove(observer);
    }
  
    public abstract void notifyObserver(a);  // Notify all observers
}
Copy the code

Actual target object

class ConcreateSubject extends Subject {
    @Override
    public void notifyObserver(a) {
        System.out.println("The target object has changed");
        for(Observer obs : observers) { obs.response(); }}}Copy the code

test

public class Demo {
    public static void main(String[] args) {
        Subject subject = new ConcreateSubject();  // The object being observed
        Observer obs1 = new Observer1();  // Observe object 1
        Observer obs2 = new Observer2();  // Observe object 2subject.add(obs1); subject.add(obs2); subject.notifyObserver(); }}Copy the code