在对象之间定义了一对多的依赖,这样一来,当一个对象改变状态,依赖它的对象会收到通知并自动更新,典型应用邮件订阅。
public interface Observer {
public void update();
}
public class Zhangsan implements Observer {
@Override
public void update() {
System.out.println("zhangsan received.");
}
}
public class Lisi implements Observer {
@Override
public void update() {
System.out.println("lisi received.");
}
}
public interface Subject {
public void register(Observer o);
public void delete(Observer o);
public void notifyAllObserver();
}
public class MySubject implements Subject {
private List<Observer> list = new ArrayList<Observer>();
@Override
public void register(Observer o) {
list.add(o);
}
@Override
public void delete(Observer o) {
list.remove(o);
}
@Override
public void notifyAllObserver() {
for(Observer o : list) {
o.update();
}
}
}
public class Test {
public static void main(String[] args) {
Observer zhangsan = new Zhangsan();
Observer lisi = new Lisi();
Subject sub = new MySubject();
sub.register(zhangsan);
sub.register(lisi);
sub.notifyAllObserver();
System.out.println("===================");
sub.delete(zhangsan);
sub.notifyAllObserver();
}
}