代码拉取完成,页面将自动刷新
//۲ģʽ
#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;
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。