观察者模式(Observer)
引用:http://blog.csdn.net/zhangerqing/article/details/8243942
当一个对象发生变化时,其他依赖该对象的对象会受到通知,并随着变化,是一对多的关系。如关系图,Mysubject类是我们的主对象,Observer1和Observer2是依赖Mysuject的对象,当Mysubject变化时,Observer1和Observer2随着变化。AbstractSubject类中定义着需要监控的对象列表,可以修改、增加或删除被监控的对象;且当Mysubject发生变化时,会通知被监控的对象。
一个Observer接口
1 public interface Observer { 2 public void update(); 3 }
两个实现类
1 public class Observer1 implements Observer { 2 @Override 3 public void update(){ 4 System.out.println("observer1 has received"); 5 } 6 }
1 public class Observer2 implements Observer{ 2 @Override 3 public void update(){ 4 System.out.println("observer2 has received"); 5 } 6 }
Subject接口及实现类
1 public class Observer2 implements Observer{ 2 @Override 3 public void update(){ 4 System.out.println("observer2 has received"); 5 } 6 }
1 public abstract class AbstractSubject implements Subject{ 2 private Vector<Observer> vector=new Vector<Observer>(); 3 @Override 4 public void add(Observer observer){ 5 vector.add(observer); 6 } 7 @Override 8 public void del(Observer observer){ 9 vector.remove(observer); 10 } 11 @Override 12 public void notifyObservers(){ 13 Enumeration<Observer> enumo=vector.elements(); 14 while(enumo.hasMoreElements()){ 15 enumo.nextElement().update(); 16 } 17 } 18 }
1 public class Mysubject extends AbstractSubject{ 2 @Override 3 public void operation(){ 4 System.out.println("update self"); 5 notifyObservers(); 6 } 7 8 }
测试类
1 public class Mytest{ 2 public static void main(String [] argus){ 3 Subject sub=new Mysubject(); 4 sub.add(new Observer1()); 5 sub.add(new Observer2()); 6 sub.operation(); 7 } 8 }