观察者模式
一、问题:定义了一个一对多的依赖关系,让多个观察者同时监听一个主题对象,当主题对象发生变化时候,会通知到所有的观察者对象
二、作用:当一个对象变化需要同时改变其他对象的时候
三、类图
(1)推的形式
(2)拉的形式
四、实现
(1)抽象主题类
public interface ISubject { public void register(IObserver observer); public void unregister(IObserver observer); public void notifyObservers(); }
(2)具体主题类
public class Subject implements ISubject { private Vector<IObserver> vec = new Vector<IObserver>(); private String data; public String getData() { return data; } public void setData(String data) { this.data = data; } @Override public void register(IObserver observer) { vec.add(observer); } @Override public void unregister(IObserver observer) { if(vec.contains(observer)) vec.remove(observer); } @Override public void notifyObservers() { for(int i = 0; i < vec.size(); i++) { vec.get(i).refresh(this); } } }
(3)抽象观察者类
public interface IObserver { public void refresh(ISubject subject); }
(4)具体观察者类
public class Observer implements IObserver { @Override public void refresh(ISubject subject) { Subject sub = (Subject)subject; System.out.println(sub.getData()); } }
(5)用户类测试类
public class Client { public static void main(String[] args) { Subject subject = new Subject(); IObserver one = new Observer(); IObserver two = new Observer(); subject.register(one); subject.register(two); subject.setData("hello world"); subject.notifyObservers(); } }