This article was compiled by Colodoo (Paper Umbrella) QQ 425343603 Reference Book illustrated Design Patterns

Observer model

  • Subject (object of observation)
  • ConcreteSubject ConcreteSubject
  • An Observer
  • ConcreteObserver ConcreteObserver


Subject (object of observation)

The Subject role represents the observed object. The Subject object defines methods for registering and deleting observers. In addition, it declares methods to “get the present state.”


ConcreteSubject ConcreteSubject

The ConcreteSubject role represents a concrete object to be observed. It notifies all registered Observer roles when its state changes.


An Observer

The Observer role indicates the Observer. The Observer role is responsible for receiving notifications of state changes from the Subject role.


ConcreteObserver ConcreteObserver

The ConcreteObserver role represents a ConcreteObserver. When its UPDATE method is called, it gets the latest state of the object to observe.


The class diagram

Code sample

The observer

/** * Observer interface **@authorColodoo (paper umbrella) ***/
public interface Observer {
    public abstract void update(Subject subject);
}
Copy the code

Concrete observer

/** ** specific observer **@authorColodoo (paper umbrella) */
public class ConcreteObserver implements Observer {
    public void update(Subject subject) {
        // Specify the logic
        // TODO}}Copy the code

To observe the object

/** * observe object **@authorColodoo (paper umbrella) **/
public abstract class Subject {
    
    // List of observers
    private ArrayList<Observer> observers = new ArrayList<Observer>();
    
    // Add an observer
    public void addObserver(Observer observer) {
        this.observers.add(observer);
    }
    
    // Delete the observer
    public void deleteObserver(Observer observer) {
        this.observers.remove(observer);
    }
    
    // Notify the observer
    public void notifyObservers(a) {
        Iterator it = observers.itrator();
        while(it.hasNext()) {
            Observer o = (Observer) it.next();
            o.update(this); }}// Get the status
    public abstract int getStatus(a);
    
    / / execution
    public abstract void execute(a);
    
    
}
Copy the code

Specific object of observation

/** * Specific observation object **@authorColodoo (paper umbrella) */
class class ContreteSubject extends Subject {
    
    / / state
    private int status = 0;
    
    // Get the status
    public int getStatus(a) {
        return this.status;
    }
    
    / / execution
    public void execute(a) {
        
        // Process logic
        // TODO
        
        // Notify the observer
        this.notifyObservers(); }}Copy the code