Observer model of design pattern

1. Brief overview

  • The observer pattern defines the one to many relationship between objects, that is, when the state of an object changes, it will tell other dependent objects to update the state accordingly.
  • In the observer mode, the object that sends the status change notification is called the subject, and the object that receives and responds to the status change is called the observer.

2. Mode structure

👉 It usually consists of a topic interface (responsible for defining a series of method interfaces for managing, maintaining and notifying observers), multiple specific topic classes (responsible for implementing the internal logic of observer registration, removal, notification and other functions), an observer interface (responsible for defining the method interface for receiving notifications and updating), and multiple specific observer classes (responsible for implementing different update internal logic for different observers) and a customer class (responsible for calling the topic class and Observer class).

3. Implementation code

give an example 💡 : Suppose there is a news website available for users to subscribe to. When the website publishes new news, each subscriber will be notified of the update. Then we can use the observer mode to deal with this process.

Publisher interface

public interface Publish {
    void register(Observer observer);

    void remove(Observer observer);

    void notify();
}

News Publisher

public class NewsPublish implements Publish {
    private String news;
    
    private List<Observer> observers;

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

    public void setNews(String content) {
        this.news = content;
    }

    @Override
    public void register(Observer observer) {
        observers.add(observer);
    }

    @Override
    public void remove(Observer observer) {
        if (observers.contains(observer)) {
            observers.remove(observer);
        }
    }

    @Override
    public void notify() {
        for (Observer observer : observers) {
            observer.update(news);
        }
    }
}

Observer interface

public interface Observer {
    void update(String content);
}

Observer

public class UserObserver implements Observer {

    @Override
    public void update(String content) {
        System.out.println("News update: " + content);
    }
}

Customer class

// Test client
public class ObserverClient{
    public static void main(String[] args) {
		// Create observer
        Observer o1 = new UserObserver();
        Observer o2 = new UserObserver();
        
        // Create publisher
        Publish publish = new NewsPublish();
        publish.add(o1);
        publish.add(o2);
        
        // Update content and notify observers
        publish.setNews("New news");
        publish.notify();
    }
}

4. Advantages and benefits

  • Observer mode establishes an abstract coupling between the observed and the observer. Because the observed and the observer are not closely coupled, they can belong to different abstraction levels.
  • In the observer mode, we can add and remove specified observers at will without changing the internal logic of the publisher, so it complies with the OCP principle.

5. Disadvantages

  • If an observed object has many direct and indirect observers, it will take a lot of time to notify all observers.
  • If there is a circular dependency between the observers, the observers are likely to make circular calls during execution, resulting in system crash.

6. Application scenarios

  • It is used when we want to implement functions similar to broadcast mechanism in the system.
  • It is used when the state of an object needs to be updated synchronously with other associated objects, and the number of other objects can be changed dynamically.
  • It is used when an object only needs to notify other objects of its own updates without letting other objects know the internal details.

7. Application examples

Observable class in JDK source code

  1. The Observable class here is equivalent to the topic class in the observer mode, but it does not implement any interface and is implemented directly.

  2. We can see that the Observable class also defines a series of methods for adding observers, removing observers, and notifying observers.

  3. The Observer class here is the observer interface, which defines the update method for notifying updates.

  4. Therefore, from the above process analysis, we can see that the Observable class in JDK is designed to use the observer pattern.

Keywords: Java Design Pattern

Added by phpfreak101 on Sat, 23 Oct 2021 19:28:32 +0300