Java之观察者模式
1.概念
定义一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。
2.UML图
3.代码
interface Subject
{
public void attach(Observer observer);
public void detach(Observer observer);
void notifyObservers();
}
public class ConcreteSubject implements Subject
{
private Vector observersVector = new Vector();
public void attach(Observer observer) {
observersVector.addElement(observer);
}
public void detach(Observer observer){
observersVector.removeElement(observer);
}
public void notifyObservers(){
Enumeration enumeration = observersVector.clone()).elements();
while (enumeration.hasMoreElements()){
((Observer)enumeration.nextElement()).update();
}
}
}
public interface Observer {
void update();
}
public class ConcreteObserver1 implements Observer{
public void update() {
System.out.println("Obsver1 execute");
}
}
public class ConcreteObserver2 implements Observer{
public void update() {
System.out.println("Obsver2 execute");
}
}
public class Main {
public static void main(String[] args) {
ConcreteSubject concreteSubject = new ConcreteSubject ();
ConcreteObserver1 observer1 = new ConcreteObserver1();
ConcreteObserver2 observer2 = new ConcreteObserver2();
generator.addObserver(observer1);
generator.addObserver(observer2);
concreteSubject.notifyObservers();
}
}
4.应用场景
当对一个对象的改变需要同时改变其它对象,依赖于它的对象都需要改变时。
--------------------------------------------------------------------
PS: 欢迎关注公众号"Devin说",会不定期更新Java相关技术知识。
--------------------------------------------------------------------