当前位置:天才代写 > tutorial > C语言/C++ 教程 > 设计模式–调查者模式(C++)

设计模式–调查者模式(C++)

2017-11-04 08:00 星期六 所属: C语言/C++ 教程 浏览:404

作者:刘勉刚 E-mail:[email protected]

调查者模式是应用很是遍及的设计模式之一,前面已经用C#实现了,下面是C++的实现,在C++实现中,C++中没有接口的观念,可是可以用抽象类类取代Java或C#中的接口,在C++中抽象类中从派生类中抽象出来的函数(要领),必需界说成纯虚函数,这样在后头的利用中才可以通过基类的指针来会见这些函数,面向工具的语言中有个特点,多态只能会见两者中共有的部门。

#include
#include
#include
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
*l;
public:
Earth()
{
l = new list
();
}
void attach(Observer *o)
{
this->l->push_back(o);
};
void change()
{
for(list
::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;
}

 

    关键字:

天才代写-代写联系方式