1 观察者模式
当一个对象被修改时,则会自动通知它的依赖对象。观察者模式属于行为型模式。定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新
2 类图
3 代码实现
1)Observer.java
public abstract class Observer { protected Subject subject; public abstract void update(); }
2)AddObserver.java
public class AddObserver extends Observer{ public AddObserver(Subject subject){ this.subject = subject; this.subject.attach(this); } @Override public void update() { System.out.println( "add value is: " + (subject.getState() + subject.getState())); } }
3)SubObserver.java
public class SubObserver extends Observer{ public SubObserver(Subject subject){ this.subject = subject; this.subject.attach(this); } @Override public void update() { System.out.println( "sub value is: " + (subject.getState() - 5)); } }
4)Subject.java
import java.util.ArrayList; import java.util.List; public class Subject { private List<Observer> observers = new ArrayList<Observer>(); private int state; public int getState() { return state; } public void setState(int state) { this.state = state; notifyAllObservers(); } public void attach(Observer observer){ observers.add(observer); } public void notifyAllObservers(){ for (Observer observer : observers) { observer.update(); } } }
5)Test.java
public class Test { public static void main(String[] args) { Subject subject = new Subject(); new AddObserver(subject); new SubObserver(subject); System.out.println("add value state to 5"); subject.setState(5); System.out.println("add value state to 8"); subject.setState(10); } }
4 运行结果
add value state to 5 add value is: 10 sub value is: 0 add value state to 5 add value is: 16 sub value is: 3