当前位置导航:炫浪网>>网络学院>>编程开发>>C++教程>>C++进阶与实例

基础入门:观察者模式C++

 // codetest.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include
using namespace std;
class Observer;
class Subject
{
public:
virtual void Attach(Observer *o)=0;
virtual void Change()=0;
virtual char * toString()=0;
};
class Observer
{
public:
virtual void Update(Subject *s)=0;
};
class Teacher:public Subject
{
public:
Teacher()
{
Oblist=new Observer * [3];
sCount=0;
}
void Attach(Observer *o){
Oblist[sCount++]=o;
}
void Change(){
for(int i=0;i<3;i++)>Update(this);
}
char * toString()
{
return "Teacher X";
}
private:
Observer **Oblist;
int sCount;
};
class Student:public Observer
{
public:
Student(char * str)
{
myName=str;
}
void Update(Subject *s)
{
cout<
<
toString()<
}
private:
char * myName;
};
int _tmain(int argc, _TCHAR* argv[])
{
Student *s1=new Student("A");
Student *s2=new Student("B");
Student *s3=new Student("C");
Teacher t;
t.Attach(s1);
t.Attach(s2);
t.Attach(s3);
t.Change();
return 0;
}
相关内容
赞助商链接