快速业务通道

设计模式--观察者模式(C++)

作者 佚名技术 来源 程序设计 浏览 发布时间 2012-06-29

作者:刘勉刚 E-mail:liumgj@163.com

观察者模式是应用非常广泛的设计模式之一,前面已经用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;
}

凌众科技专业提供服务器租用、服务器托管、企业邮局、虚拟主机等服务,公司网站:http://www.lingzhong.cn 为了给广大客户了解更多的技术信息,本技术文章收集来源于网络,凌众科技尊重文章作者的版权,如果有涉及你的版权有必要删除你的文章,请和我们联系。以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!

分享到: 更多

Copyright ©1999-2011 厦门凌众科技有限公司 厦门优通互联科技开发有限公司 All rights reserved

地址(ADD):厦门软件园二期望海路63号701E(东南融通旁) 邮编(ZIP):361008

电话:0592-5908028 传真:0592-5908039 咨询信箱:web@lingzhong.cn 咨询OICQ:173723134

《中华人民共和国增值电信业务经营许可证》闽B2-20100024  ICP备案:闽ICP备05037997号