观察者模式很好理解,类似于邮件订阅和RSS订阅,当我们浏览一些博客或wiki时,经常会看到RSS图标,就这的意思是,当你订阅了该文章,如果后续有更新,会及时通知你。其实,简单来讲就一句话:当一个对象变化时,其它依赖该对象的对象都会收到通知,并且随着变化
一个Observer接口
public interface Observer {
public void update();
}
两个实现类
public class Observer1 implements Observer{
@Override
public void update() {
// TODO Auto-generated method stub
System.out.print("lijunwei Observer1 update");
}
}
public class Observer2 implements Observer {
@Override
public void update() {
// TODO Auto-generated method stub
System.out.print("lijunwei Observer2 update");
}
}
public interface Subject {
/*增加观察者*/
public void add (Observer observer);
/*删除观察者*/
public void del(Observer observer);
/*通知所有的观察者*/
public void notification();
/*自身的操作*/
public void operation();
}
public abstract class AbstractSubject implements Subject {
private Vector<Observer> ob =new Vector<Observer>();
@Override
public void del(Observer observer) {
// TODO Auto-generated method stub
ob.add(observer);
}
@Override
public void add(Observer observer) {
// TODO Auto-generated method stub
ob.add(observer);
}
@Override
public void notification() {
// TODO Auto-generated method stub
//将enumo赋值
Enumeration<Observer> enumo=ob.elements();
while(enumo.hasMoreElements()) {
//若有更多元素 则调用update 方法
enumo.nextElement().update();
}
}
}
public class MySubject extends AbstractSubject {
public void operation(){
System.out.print("new sms");
notification();
}
}
测试类:
public class Test {
public static void main(String[] args) {
MySubject ss =new MySubject();
ss.add(new Observer1());
ss.add(new Observer2());
ss.operation();
}
}
输出
new sms
lijunwei Observer1 update
lijunwei Observer2 update