Skip to content

Instantly share code, notes, and snippets.

@bugparty
Created July 19, 2016 09:06
Show Gist options
  • Save bugparty/639d6e8bb9c948e6d13e866675cce7c8 to your computer and use it in GitHub Desktop.
Save bugparty/639d6e8bb9c948e6d13e866675cce7c8 to your computer and use it in GitHub Desktop.
java观察者
/*
观察者接口
*/
interface Observer<T>{
/*
接受更新的状态
*param state 新的状态
*/
void update(T state);
}
/*
通知观察者的主题类
*/
static abstract class Subject<StateClass>{
private List<Observer<StateClass>> observers;
void notifyObservers(StateClass newState){
for (Observer o:observers
) {
o.update(newState);
}
}
/*
注册观察者
*param o 观察者
*/
void attach(Observer o) {
observers.add(o);
}
/*
反注册观察者
*param o 观察者
*/
void deattach(Observer o) {
observers.remove(o);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment