#include<iostream>
#include<list>
class Subject;
//观察员基类
class Observer {
public:
//绑定到被观察员
Subject* subject;
virtual void Update() = 0;
};
//被观察员
class Subject {
std::list<Observer*> observers;
std::string message;
public:
//得到状态
std::string GetMessage() {
return message;
}
//设置状态
void SetMessage(std::string s) {
message = s;
//状态发生改变通知所有观察员
NotifyAllObservers();
}
void Attach(Observer* ob) {
//添加观察员
observers.push_back(ob);
}
//通知所有观察员
void NotifyAllObservers() {
for (auto& obs : observers) {
obs->Update();
}
}
};
//路灯王
class Observer_Archer :public Observer {
public:
Observer_Archer(Subject* sjt) {
subject = sjt;
}
//ea
void Update()override {
//得到通知后执行细节。。。
if (subject->GetMessage() == "open ea !") {
std::cout << "The star of breaking new ground !" << std::endl;
}
else {
std::cout << "杂修!" << std::endl;
}
}
};
//红A
class Observer_RedArcher :public Observer {
public:
Observer_RedArcher(Subject* sjt) {
subject = sjt;
}
//无限剑制
void Update()override {
//得到通知后执行细节。。。
if (subject->GetMessage() == "open unlimited blade works") {
std::cout << "My whole life was unlimited blade works !" << std::endl;
}
else {
std::cout << "真是麻烦啊!" << std::endl;
}
}
};
//阿尔托莉雅
class Observer_Saber :public Observer {
public:
Observer_Saber(Subject* sjt) {
subject = sjt;
}
//圣剑
void Update()override {
//得到通知后执行细节。。。
if (subject->GetMessage() == "open excalibur") {
std::cout << "Excalibur" << std::endl;
}
else {
std::cout << "是你在召唤我吗!" << std::endl;
}
}
};
int main()
{
//创建被观察员
Subject* subject = new Subject();
//召唤金闪闪
Observer* ob_archer = new Observer_Archer(subject);
//召唤红A
Observer* ob_redArcher = new Observer_RedArcher(subject);
//召唤saber
Observer* ob_saber = new Observer_Saber(subject);
//建立契约
subject->Attach(ob_archer);
subject->Attach(ob_redArcher);
subject->Attach(ob_saber);
std::string message[3]{ "open ea !","open unlimited blade works","open excalibur"};
for (auto& s : message) {
subject->SetMessage(s);
std::cout << "\n";
}
system("pause");
return 0;
}
设计模式之观察者模式
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...