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
public class Observable {
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;
}
public void addObserver(Observer o){
if(o != null && !observerList.contains(o)){
observerList.add(o);
}
}
public void removeObserver(Observer o){
observerList.remove(o);
}
public void notifyObservers(){
Iterator<Observer> iterator = observerList.iterator();
while (iterator.hasNext())
iterator.next().update(this);
}
}
public interface Observer {
public void update(Observable observable);
}
public class NumBerObserver implements Observer {
@Override
public void update(Observable observable) {
int num = observable.getNum();
System.out.println(num);
}
}
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("*");
}
}
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