01观察者模式

1. 目标基类
//subject.h
#pragma once
#include <list>
#include "observer.h"


class Subject
{
public:
	virtual ~Subject()
	{}

	//注册
	virtual void attach(Observer* obsv)
	{
		if (nullptr != obsv)
		{
			m_listObsv.push_back(obsv);
		}
	}

	//反注册
	virtual void detach(Observer* obsv)
	{
		for (auto it = m_listObsv.begin();
			it != m_listObsv.end(); ++it)
		{
			if (*it == obsv)
			{
				m_listObsv.erase(it);
				return;
			}
		}
	}

	//通知
	virtual void notify()
	{
		for (auto it = m_listObsv.begin();
			it != m_listObsv.end(); ++it)
		{
			(*it)->update(this);
		}
	}

protected:
	Subject()
	{}

private:
	std::list<Observer*> m_listObsv;
};

2. 观察者基类
//observer.h
#pragma once
class Subject;
class Observer
{
public:
	virtual ~Observer()
	{}
	virtual void update(Subject* theChangedSubject) = 0;

protected:
	Observer()
	{}
};


3. 目标实现类
//clock_subject.h
#pragma once

#include "subject.h"
class ClockSubject :
	public Subject
{
public:
	ClockSubject();
	virtual ~ClockSubject();

	virtual int getHour();
	virtual int getMinute();
	virtual int getSecond();

	void tick();
};
//clock_subject.cpp
#include "clock_subject.h"
#include<chrono>
#include<thread>

using namespace std;


ClockSubject::ClockSubject()
{
}

ClockSubject::~ClockSubject()
{
}

int ClockSubject::getHour()
{
	auto tt = std::chrono::system_clock::to_time_t
		(std::chrono::system_clock::now());
	struct tm* ptm = localtime(&tt);
	return ptm->tm_hour;
}

int ClockSubject::getMinute()
{
	auto tt = std::chrono::system_clock::to_time_t
		(std::chrono::system_clock::now());
	struct tm* ptm = localtime(&tt);
	return ptm->tm_min;
}

int ClockSubject::getSecond()
{
	auto tt = std::chrono::system_clock::to_time_t
		(std::chrono::system_clock::now());
	struct tm* ptm = localtime(&tt);
	return ptm->tm_sec;
}


void ClockSubject::tick()
{
	while (true)
	{
		notify();
		std::this_thread::sleep_for(std::chrono::seconds(2));		
	}
}
4. 观察者实现类
//app1_observer.h
#pragma once
#include "observer.h"
#include "clock_subject.h"

class App1Observer :
	public Observer
{
public:
	App1Observer(ClockSubject* clockSubj);
	virtual ~App1Observer();

	virtual void update(Subject* subj);

private:
	ClockSubject* m_clockSubj;
};


//app1_observer.cpp
#include "app1_observer.h"
#include <iostream>
using namespace std;


App1Observer::App1Observer(ClockSubject* clockSubj)
{
	m_clockSubj = clockSubj;
	m_clockSubj->attach(this);
}


App1Observer::~App1Observer()
{
	m_clockSubj->detach(this);
}

void App1Observer::update(Subject* subj)
{
	if (m_clockSubj != subj)
	{
		return;
	}
	//获取状态
	int hour = m_clockSubj->getHour();
	int min = m_clockSubj->getMinute();
	int sec = m_clockSubj->getSecond();
	//处理业务
	cout << "current time: " << hour << ":" << min << ":" << sec << endl;

}

5. demo
//main.cpp
#include "clock_subject.h"
#include "app1_observer.h"
using namespace std;

int main()
{
	ClockSubject clock;
	App1Observer app1(&clock);
	clock.tick();

	return 0;
}

imager

posted @ 2020-06-26 18:14  洛克十年  阅读(136)  评论(0编辑  收藏  举报