Observer pattern
-behavioral pattern 중 하나이다.
-객체간 1:N 관계일 경우 사용된다.
-하나의 객체가 변경되면 의존하는 객체들은 모두 자동으로 통지 받는다.
3개의 actor class로 구성된다.
Subject : client에 observer들을 attach 또는 detach 하는 역할.
Observer : subject에 등록되며 통지를 받음 통지내용은 update함수의 구현에 따라 다르다.
Client : 해당 예제에서는 Subject가 client 역할도 하는 것으로 보인다.
Main 호출 부분:
Subject subject = new Subject();
new HexaObserver(subject);
new OctalObserver(subject);
new BinaryObserver(subject);
Log.d("hello","First state change :15");
subject.setState(15);
Log.d("hello","First state change :10");
subject.setState(10);
Subject.java
observer를 관리하는 객체로 observer의 등록/해제 및 상태 변화시 통지 하는 역할을 한다.
public class Subject {
private List observers = new ArrayList();
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 o : observers){
o.update();
}
}
}
Observer.java
Subject를 멤버로 가지며 상태변화시 사용될 update 메소드를 가진다.
public abstract class Observer {
protected Subject subject;
public abstract void update();
}
나머지 Observer class
객체 생성시, subject에 등록되며 update함수를 정의한다.
public class BinaryObserver extends Observer {
public BinaryObserver(Subject subject){
this.subject=subject;
this.subject.attach(this);
}
@Override
public void update() {
Log.d("hello","Binary String : "+Integer.toBinaryString(subject.getState()));
}
}
public class HexaObserver extends Observer {
public HexaObserver(Subject subject){
this.subject = subject;
this.subject.attach(this);
}
@Override
public void update() {
Log.d("hello", "Hexa String : "+ Integer.toHexString(subject.getState()));
}
}
public class OctalObserver extends Observer {
public OctalObserver(Subject subject){
this.subject=subject;
this.subject.attach(this);
}
@Override
public void update() {
Log.d("hello", "Octal String : "+ Integer.toOctalString(subject.getState()));
}
}
결과:
07-25 10:10:56.697 10940 10940 D hello : First state change :15
07-25 10:10:56.698 10940 10940 D hello : Hexa String : f
07-25 10:10:56.698 10940 10940 D hello : Octal String : 17
07-25 10:10:56.698 10940 10940 D hello : Binary String : 1111
07-25 10:10:56.698 10940 10940 D hello : First state change :10
07-25 10:10:56.698 10940 10940 D hello : Hexa String : a
07-25 10:10:56.698 10940 10940 D hello : Octal String : 12
07-25 10:10:56.698 10940 10940 D hello : Binary String :
출처 :
'pattern' 카테고리의 다른 글
| uml 화살표 의미 (0) | 2020.07.31 |
|---|---|
| Memento pattern (0) | 2018.07.24 |
| Mediator pattern (0) | 2018.07.24 |
| Iterator Pattern (0) | 2018.07.24 |
| Interpreter pattern (0) | 2018.07.20 |