프로그래밍/GoF

[행동 패턴] - 감시자(Observer)

MAKGA 2022. 1. 8. 10:40
320x100

구조

#pragma once

#include <iostream>
#include <set>
#include <string>

class Observer
{
public:
    virtual void update() = 0;
};

class Subject
{
private:
    std::set<Observer*> observers_;

public:
    void attach(Observer* observer)
    {
        observers_.insert(observer);
    }

    void detach(Observer* observer)
    {
        observers_.erase(observer);
    }

    void notify()
    {
        for (Observer* observer : observers_)
        {
            observer->update();
        }
    }
};

class ConcreteSubject : public Subject
{
private:
    std::string subjectState_;

public:
    std::string& getState()
    {
        return subjectState_;
    }

    void setState(std::string& state)
    {
        subjectState_ = state;
    }
};

class ConcreteObserver : public Observer
{
private:
    ConcreteSubject* subject_;
    std::string observerState_;

public:
    ConcreteObserver(ConcreteSubject* subject)
    {
        subject_ = subject;
        subject_->attach(this);
    }

    void update()
    {
        std::cout << "updated" << std::endl;
        observerState_ = subject_->getState();
    }
};

 

사용

int main()
{
    ConcreteSubject* subject = new ConcreteSubject;
    ConcreteObserver* observer1 = new ConcreteObserver(subject);
    ConcreteObserver* observer2 = new ConcreteObserver(subject);

    subject->notify();
    subject->detach(observer1);
    subject->notify();

    system("pause");

    return 0;
}

 

어느 이벤트가 발생하는 객체(ConcreteSubject)에 이벤트가 발생하면 통보받을 객체(ConcreteObserver)들을 등록해두고, 사건이 발생하면 ConcreteSubject는 자신에게 등록된 ConcreteObserver 목록을 돌며 이벤트를 통지해준다.

320x100