Design Patterns/Behavioral Patterns

Observer Pattern (C++)

개발새발 2019. 3. 24. 23:11
반응형

Observer Pattern (감시자 패턴)

목적

어떤 객체의 상태가 변할 때 그 객체의 변화를 통지받기(Notify)를 원하는 다른 객체들이(옵저버) 그 변화를 통지받을 수 있도록 한다.
통지는 각각의 옵저버들이 변화된 객체로부터 콜백(callback)을 받는다.

https://ko.wikipedia.org/wiki/%EC%98%B5%EC%84%9C%EB%B2%84_%ED%8C%A8%ED%84%B4



사용 시나리오

1. 시간정보를 가지고 있는 클래스가 있다.
2. 디지털 시계 위젯과 아날로그 시계 위젯이 시간정보 객체로부터 시간의 변할때마다 통지를 받고싶다.
3. 시간이 변할 때마다 시간정보 클래스에서 옵저버객체들에게 변화를 알린다.

[Subject]

시간 정보를 가지고 있는 클래스이며 옵저버의 등록을 받아 옵저버를 리스트로 저장해 두었다가 시간이 변할 때 알려 준다.

class ClockTimer { public: void RegisterObserver(TimeObserver* observer) { observerList.push_back(observer); } void Detach(TimeObserver* observer){ } void Tick() { cout<<"time is ticking"<<endl;

NotifyObservers();

}

private:

vector<TimeObserver*> observerList; void NotifyObservers() { double currentTime = 0; for(int i = 0; i < observerList.size(); i++) { TimeObserver* observer = observerList[i]; observer->Update(currentTime); } } };


[Observer]

시간정보를 받기를 원하는 옵저버 객체들의 규약을 정하는 Observer 인터페이스
class TimeObserver {
public:
    virtual ~TimeObserver(){};
    virtual void Update(double time) = 0;
};


[Concrete Observer]

Observer인터페이스를 통해 Notify를 구현한 클래스
class DigitalTimeObserver : public TimeObserver {
public:
    virtual void Update(double time) {
        cout<<"Update digital time"<<endl;
    }
};

class AnalogTimeObserver : public TimeObserver {
public:
    virtual void Update(double time) {
        cout<<"Update analog time"<<endl;
    }
};


[사용 예 main]

int main(int argc, const char * argv[]) {
    AnalogTimeObserver* analogTimeObserver = new AnalogTimeObserver();
    DigitalTimeObserver* digitalTimeObserver = new DigitalTimeObserver();
    
    ClockTimer* timer = new ClockTimer();
    timer->RegisterObserver(analogTimeObserver);
    timer->RegisterObserver(digitalTimeObserver);
    
    timer->Tick();//시간상태 변함

    return 0;
}


실행결과

time is ticking

Update analog time

Update digital time


반응형