⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 main.cpp

📁 观察者模式
💻 CPP
字号:
#include <iostream>
#include <string>
#include <list>
using namespace std;

class Observer;
class Subject
{
public:
	virtual void attach(Observer *o)=0;
	virtual void change()=0;
	virtual void setWeather(string str)=0;
	virtual string getWeather()=0;
};
class Observer
{
public:
	virtual string getName()=0;
	virtual void update(Subject *s)=0;
};

class Earth:public Subject
{
private:
	string weather;
	list<Observer*> *l;
public:
 	Earth()
 	{
 	//	l = new list();
 	}
	void attach(Observer *o)
	{
		l->push_back(o);
	};
	void change()
	{
		for(list<Observer*>::iterator it=l->begin();it!=l->end();++it)
		{
			(*it)->update(this);
		}
	};
	void setWeather(string str)
	{
		this->weather=str;
		change();
	};
	string getWeather()
	{
		return this->weather;
	};
};
class Satellite:public Observer
{
private:
	string name;
public:
	Satellite(string str)
	{
		name=str;
	}
	string getName()
	{
		return name;
	};
	void update(Subject *s)
	{
		cout<<this->getName()+" "+s->getWeather();
	};
};

int main()
{
	Earth e;
	Satellite *s1 = new Satellite("风云一号");
	Satellite *s2 = new Satellite("风云二号");
	Satellite *s3 = new Satellite("风云三号");
	Satellite *s4 = new Satellite("风云四号");
	e.attach(s1);
	e.attach(s2);
	e.attach(s3);
	e.attach(s4);
	e.setWeather("fine");
	return 0;
} 

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -