전문가 위한 c++: 옵저버 패턴.

보물창고·2024년 1월 1일
0
#include <iostream>
using namespace std;
#include <string>

#include <vector>
#include <limits.h>
#include <algorithm>
#include <map>
#include <future>
#include <thread>
#include <numeric>
#include <stack>
#include <queue>
#include <memory>
#include <set>
#include <string>
#include <stack>
#include <mutex>


using EventHandler = size_t;

template <typename... Args>
class Event
{
public : 
	virtual ~Event() = default;

	EventHandler operator+= (function<void(Args...)> observer)
	{
		auto num{ ++mCnt };
		mObservers[num] = observer;
		return num;
	}

	Event& operator-=(EventHandler handle)
	{
		mObservers.erase(handle);
		return *this;
	}

	void raise(Args... args)
	{
		for (auto & observer : mObservers)
		{
			(observer.second)(args...);
		}
	}

private : 
	size_t mCnt{ 0 };
	map<EventHandler, function<void(Args...)>> mObservers;

};

class Subject
{
public : 
	auto& getEventDataModified() { return mEventDataModified; }
	auto& getEventDataDelete() { return mEventDataDelete;  }

	void modify()
	{
		getEventDataModified().raise(1, 2.3);
	}
	void deleteData()
	{
		getEventDataDelete().raise();
	}


private : 
	Event<int, double> mEventDataModified;
	Event<> mEventDataDelete;
};

void modified(int a, double d) { cout << "modify" << endl; cout << "resutl : " << a + d << endl; }

class Observer
{
public : 
	Observer(Subject& sub) 
		: mSubject{sub}
	{
		mSubjectModifyHandler = mSubject.getEventDataModified()
			+= [this](int i, double d) { onSubjectModify(i, d); };
	}
	virtual ~Observer()
	{
		mSubject.getEventDataModified() -= mSubjectModifyHandler;
	}

private : 
	void onSubjectModify(int, double)
	{
		cout << "Observer::onSubjectModify()" << endl;
	}

	Subject& mSubject;
	EventHandler mSubjectModifyHandler;

};



int main()
{
	Subject sub;

	auto handleModify{ sub.getEventDataModified() += modified };
	auto handleDeleted{ sub.getEventDataDelete() += [] {cout << "deleted" << endl; } };
	Observer observer{ sub };

	sub.modify();
	sub.deleteData();
	cout << endl;

}

profile
🔥🔥🔥

0개의 댓글