Design Pattern-03. Observer Pattern

Design Pattern-03. Observer Pattern

Observer mode

The observer mode is a message distribution mode, which can promptly notify the observer of the state of the observer.

For example, when a supermarket has a discount, it is necessary to notify each supermarket customer, so that the supermarket can be regarded as an observer, and the customer is an observer.

Implementation logic

The class diagram implemented by the observer pattern is as follows:

Implementation steps:

  1. Define an Observer interface to constrain the methods that observers (customers) need to implement:
    
 public interface Observer {
     void reciveMessage(double price);
 }

 public class CusmtomerObserver1 implements Observer {
     @Override
     public void reciveMessage(double price) {
            
         System.out.println("CusmtomerObserver1 received price message:" + price);
     }
 }

 public class CusmtomerObserver2 implements Observer {
     @Override
     public void reciveMessage(double price) {
            
         System.out.println("CusmtomerObserver2 received price message:" + price);
     }
 }
  1. Method of implementing the observed object
 public class MarketSubject {
     private double price;
     public double getPrice() {
         return price;
     }
    
     public void setPrice(double price) {
         this.price = price;
         notifyObserver(price);
     }
        
     private ArrayList<Observer> observerList=new ArrayList<>();
     public void addObserver(Observer observer){
         observerList.add(observer);
     }
        
     public void removeObserver(Observer observer){
         observerList.remove(observer);
     }
        
     public void notifyObserver(double price){
         for (Observer ob: observerList) {
             ob.reciveMessage(price);
         }
     }
 }
 
 
  1. Registration and notification of implementation methods
 public class ObserverMain {
     public static void main(String[] args) {
         MarketSubject marketSubject=new MarketSubject();
         marketSubject.addObserver(new CusmtomerObserver1());
         marketSubject.addObserver(new CusmtomerObserver2());
         marketSubject.setPrice(100d);
        
     }
 }

operation result:

CusmtomerObserver1 received price news: 100.0
CusmtomerObserver2 received price news: 100.0

(End of this article)

Author: Fu Weibo passenger address: http://blog.laofu.online If you have any intellectual property rights, copyright issues or theory wrong, please correct me. This article is the original web blog of Fu Wei , freely reprinted-non-commercial-non-derivative-keep the signature, please follow: Creative Commons 3.0 License

Reference: https://cloud.tencent.com/developer/article/1584321 Design Pattern-03. Observer Pattern-Cloud + Community-Tencent Cloud