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

📄 redgreen.cpp

📁 自己写的红绿灯的例子!呵呵
💻 CPP
字号:
// ww.cpp : Defines the entry point for the console application.
//

#include <vector>
#include <iostream>
#include <string>
#include <set>
using namespace std;

class Subject;

class Observer
{
public:
	virtual ~Observer(){}
	virtual int Update(Subject* theChangedSubject,int i) = 0;
protected:
	Observer(){}

};

class Subject
{
protected:
	Subject(){}
public:
	~Subject(){}
	virtual int GetID(){return 0;}
	void Attatch(Observer* o)
	{
		_Observers.insert(o);
	}
	void Detach(Observer* o)
	{
		_Observers.erase(o);
	}
	void Notify(int i)
	{
		for(set<Observer*>::iterator it=_Observers.begin();
			it!=_Observers.end();++it)
		{
			(*it)->Update(this,i);
		}
	}

protected:
	set<Observer*> _Observers;
};

class CFiftyControl : public Subject
{		
public:
	int GetID(){return 50;}
	CFiftyControl(){}

};

class CSixtyControl : public Subject
{	
public:
	int GetID(){return 60;}
	CSixtyControl(){}

};

class CCrossLight:public Observer
{
public:
	CCrossLight(int n,string state){m_id = n;m_State=state;}
	virtual int Update(Subject* theChangedSubject,int i) 
	{
		if(theChangedSubject->GetID()==50)
		{
			if(m_State=="GREEN")
			{
				m_State="YELLOW";
				cout<<i<<"\t"<<m_id<<" green => yellow"<<endl;
			}
			return 0;
		}
		else if(theChangedSubject->GetID()==60)
		{
			if(m_State == "Green")
			{
				exit(0);
			}
			else if(m_State == "YELLOW")
			{
				m_State = "RED";
				cout<<i<<"\t"<<m_id<<" yellow => red"<<endl;
			}
			else if(m_State == "RED")
			{
				m_State = "GREEN";
				cout<<i<<"\t"<<m_id<<" red => green"<<endl;
			}		
		}

		return 0;
	}
	string GetState(){return m_State;}
private:
	string m_State;
	int		m_id;
};

class CControlCenter
{
public :
	int Run()
	{
		int n=0;
		do
		{
			for(int i=1;i<61;i++)
			{
				if(i%50==0)
				{
					cout<<"========="<<endl;
					fifty.Notify(i);
				}

				else if(i%60==0)
					sixty.Notify(i);
			}
		}while(n++<4);

		return 0;
	}
	void AddConttolee(Observer* s)
	{
		fifty.Attatch(s);
		sixty.Attatch(s);
	}
private:
	int m_Time;
	CFiftyControl fifty;
	CSixtyControl sixty;	
};
int _tmain(int argc, _TCHAR* argv[])
{
	CCrossLight northLight(2,"RED");
	CCrossLight eastLight(1,"GREEN");

	CControlCenter center;
	center.AddConttolee(&eastLight);
	center.AddConttolee(&northLight);

	center.Run();



	return 0;
}

⌨️ 快捷键说明

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