Created
July 19, 2016 09:06
-
-
Save bugparty/639d6e8bb9c948e6d13e866675cce7c8 to your computer and use it in GitHub Desktop.
java观察者
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
观察者接口 | |
*/ | |
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