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;