Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
定义一对多的对象间关系,当一个对象的状态发生了改变,通知所有的从属对象
观察者
/**
* 观察者
*/
public interface IObserver {
void update(int value);
}
/**
* 观察者1
*/
public class Observer1 implements IObserver {
@Override
public void update(int value) {
System.out.println("Observer1: myValue in Subject is now: " + value);
}
}
/**
* 观察者2
*/
public class Observer2 implements IObserver {
@Override
public void update(int value) {
System.out.println("Observer2: myValue in Subject is now: " + value);
}
}
被观察者
/**
* 主题,被观察者
*/
public interface ISubject {
/**
* 注册观察者
* @param o
*/
void register(IObserver o);
/**
* 注销观察者
* @param o
*/
void unregister(IObserver o);
/**
* 通知观察者
* @param value
*/
void notifyObservers(int value);
}
/**
* 被观察者实现
*/
public class Subject implements ISubject {
private int value;
/**
* 观察者列表
*/
List<IObserver> observersList = new ArrayList<>();
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
// 通知所有观察者
notifyObservers(value);
}
@Override
public void register(IObserver o) {
observersList.add(o);
}
@Override
public void unregister(IObserver o) {
observersList.remove(o);
}
@Override
public void notifyObservers(int updatedValue) {
for (int i = 0; i < observersList.size(); i++) {
observersList.get(i).update(updatedValue);
}
}
}
执行
public class ObserverPatternEx {
public static void main(String[] args) {
Subject sub = new Subject();
Observer1 ob1 = new Observer1();
Observer2 ob2 = new Observer2();
sub.register(ob1);
sub.register(ob2);
sub.setValue(5);
System.out.println();
sub.setValue(25);
System.out.println();
//unregister ob1 only
sub.unregister(ob1);
//Now only ob2 will observe the change
sub.setValue(100);
}
}