Design Patterns - Behavioral Observer Patterns

Definition

  • Notify the observer when the observee sends a change.

Usage scenarios

  • Publish and subscribe. Different clients pay attention to the same message.
  • For example, we subscribe to mobile phone news, WeChat public number tweets and so on.

UML diagram

code implementation

// Observed (Notifier)
public class Observable {

    //Act as information
    private int num;

    private List<Observer> observerList ;

    public Observable(List<Observer> observerList,int num) {
        this.observerList = observerList;
        this.num = num;
    }

    public int getNum() {
        return num;
    }

    //Registered observer
    public void addObserver(Observer o){
        if(o != null && !observerList.contains(o)){
            observerList.add(o);
        }
    }

    //Remove the observer
    public void removeObserver(Observer o){
        observerList.remove(o);
    }

    //Send notification to all observers
    public void notifyObservers(){
        Iterator<Observer> iterator = observerList.iterator();
        while (iterator.hasNext())
            iterator.next().update(this);
    }
}
//Observers (notified)
public interface Observer {
    //Notice of acceptance
    public void update(Observable observable);
}
// Specific observers
public class NumBerObserver implements Observer {
    @Override
    public void update(Observable observable) {
        int num = observable.getNum();
        System.out.println(num);
    }
}
// Specific observers
public class ShapeObserver implements Observer {
    @Override
    public void update(Observable observable) {
        int num = observable.getNum();
        for (int i=0;i<num;i++)
            System.out.print("*");
    }
}
// test
public class Client {
    public static void main(String[] args) {
        Observable observable = new Observable(new ArrayList<>(),5);
        Observer observer = new NumBerObserver();
        ShapeObserver shapeObserver = new ShapeObserver();
        observable.addObserver(observer);
        observable.addObserver(shapeObserver);
        observable.notifyObservers();
    }
}

summary

  • The observee sends a notice to the observer.
  • Observable is accepted in the update method of the observer in the example, because java is a single inheritance. When the observer has inherited a class, it does not apply here (this is the case in the java source package, so it is not very useful), so it is usually more appropriate to define Observable as an interface.

Keywords: Java Mobile

Added by Pandolfo on Mon, 30 Sep 2019 16:48:16 +0300