Design Patterns - Observer Pattern

Transferred from WeChat public account: "java union"

schema definition

Defines a one-to-many dependency between objects. When an object changes state, all its dependents will be notified and automatically updated. The subject (Subject) is the observed object, and all its dependents (Observer) are called observers.

 

Design Principles

Strive for loosely coupled design between interacting objects: When two objects are loosely coupled, they can still interact, but the details of each other are unclear. Since two objects that are loosely coupled have low interdependencies, the system is resilient and able to respond to changes.

UML class diagram

 

Observer Pattern Example

Define the Observed Interface

/** 
* Abstract Observer Interface* defines the methods of adding, deleting, and notifying observers
*/
public interface Subject {
public void registerObserver(Observer o);

   public void removeObserver(Observer o);

   public void notifyObservers();
}

Define the observer interface

/** 
* Abstract observer interface* defines an update() method,
* when the observer calls the notifyObservers() method, the observer's update() method will be called back
*/
public interface Observer {
public void update(String message);
}

Define the observer, implement the Subject interface, and implement the three methods of the Subject interface. At the same time, there is a List collection to save the registered observers, and when the observers need to be notified, traverse the collection.

/**
* 具体的被观察者
*/
public class ConcreteSubject implements Subject {
private List<Observer> list;
   private String message;

   public ConcreteSubject() {
list = new ArrayList<Observer>();
   }

@Override
   public void registerObserver(Observer o) {
list.add(o);
   }

@Override
   public void removeObserver(Observer o) {
if (!list.isEmpty())
list.remove(o);
   }

@Override
   public void notifyObservers() {
for (int i = 0; i < list.size(); i++) {
Observer observer = list.get(i);
           observer.update(message);
       }
}

public void send(String s) {
this.message = s;
       System.out.println("Update message:" + s); //Message update, notify all observers
       notifyObservers() ;
   }
}

Define the observer, implement the Observer interface, and implement the method

/**
* 具体的观察者
*/
public class ConcreteObserver implements Observer {
private String name;
   private String message;

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

@Override
   public void update(String message) {
this.message = message;
       read();
   }

public void read() {
System.out.println(name + " 收到消息:" + message);
   }
}

To test the observer mode, first create an observed object (company), and then create three observer objects (employees). The company first announced that he was working overtime today. Zhang Sanyi listened and quit and resigned. After that, the company released a message. Tomorrow is a holiday, Zhang San has already resigned, so he can't receive news, other observers (employees) can receive news.

/** 
* Test Observer Mode
*/
public class ObserverDemo {
public static void main(String[] args) {
ConcreteSubject subject = new ConcreteSubject();

       Observer observer1 = new ConcreteObserver("Zhang San");
       Observer observer2 = new ConcreteObserver ("Li Si");
       Observer observer3 = new ConcreteObserver("Wang Wu");

       subject.registerObserver(observer1);
       subject.registerObserver(observer2);
       subject.registerObserver(observer3);

       subject.send("Work overtime today");

       subject.removeObserver(observer1);

       subject.send("Leave tomorrow");
   }
}

operation result

更新消息:今天加班
张三 收到消息:今天加班
李四 收到消息:今天加班
王五 收到消息:今天加班
更新消息:明天放假
李四 收到消息:明天放假
王五 收到消息:明天放假

Process finished with exit code 0

Summarize

  • The observer pattern is loosely coupled. Change one of the subjects or observers, and the other will not be affected.

  • JDK also has its own observer mode, but the observer is a class rather than an interface, which limits its use and reuse capabilities. JDK built-in observer mode java.util.Observer interface, java.util.Observable class.

  • In JavaBean and Swing, there is also the design idea of ​​the observer pattern.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324649420&siteId=291194637