2 Star 1 Fork 2

咸鱼(已废弃)/设计模式C语言

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
观察者模式.txt 1.95 KB
一键复制 编辑 原始数据 按行查看 历史
Dick—_YangDi 提交于 2017-11-08 22:31 . fist all file
//۲ģʽ
#include<iostream>
#include<vector>
using namespace std;
class Subject;//۲߻
class Observer{
private:
Subject * t;
public:
Observer(Subject * t){this->t=t;}
virtual void Updata(int){};
virtual void Updata(int,int){};
virtual void Fun()=0;
virtual ~Observer(){}
};//۲߻
class ObserverA:public Observer{
private:
int x,y;
public:
ObserverA(Subject * t):Observer(t){
x=0;
y=0;
}
void Updata(int x,int y){
this->x=x;
this->y=y;
}
void Fun(){
cout<<x<<" "<<y<<endl;
}
};
class ObserverB:public Observer{
private:
int z;
public:
ObserverB(Subject * t):Observer(t){
z=0;
}
void Updata(int z){
this->z=z;
}
void Fun(){
cout<<z<<endl;
}
};
class Subject{
protected:
vector<Observer *> vec;
public:
void Add(Observer * t){
vec.push_back(t);
}
};
class SubjectA:public Subject{
private:
int x,y;
public:
SubjectA(int x=0,int y=0){
this->x=x;
this->y=y;
}
void Notify(){
vector<Observer *>::iterator it;
for(it=vec.begin();it!=vec.end();it++)
(*it)->Updata(x,y);
}
void Datachange(int x,int y)
{
this->x=x;
this->y=y;
Notify();
}
};
class SubjectB:public Subject{
private:
int z;
public:
SubjectB(int z=0){
this->z=z;
}
void Notify(){
vector<Observer *>::iterator it;
for(it=vec.begin();it!=vec.end();it++)
(*it)->Updata(z);
}
void Datachange(int z)
{
this->z=z;
Notify();
}
};
int main(void)
{
SubjectA * pa=new SubjectA(1,2);
ObserverA * ba1=new ObserverA(pa);
ObserverA * ba2=new ObserverA(pa);
pa->Add(ba1);
pa->Add(ba2);
pa->Notify();
ba1->Fun();
ba2->Fun();
pa->Datachange(5,6);
ba1->Fun();
ba2->Fun();
delete pa;
delete ba1;
delete ba2;
SubjectB * pb=new SubjectB(1);
ObserverB * bb1=new ObserverB(pb);
ObserverB * bb2=new ObserverB(pb);
pb->Add(bb1);
pb->Add(bb2);
pb->Notify();
bb1->Fun();
bb2->Fun();
pb->Datachange(5);
bb1->Fun();
bb2->Fun();
delete pb;
delete bb1;
delete bb2;
return 0;
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/Dick_YangDi/SheJiMoShi.git
git@gitee.com:Dick_YangDi/SheJiMoShi.git
Dick_YangDi
SheJiMoShi
设计模式C语言
master

搜索帮助