观察者模式
#include <iostream>#include <list>
using namespace std;
namespace observer_pattern {
// 抽象一个信息更新类 也就是观察者
class abstract_info
{
public:
virtual void update_info() = 0;
~abstract_info() {}
};
// 表格
class form : public abstract_info
{
public:
virtual void update_info() override {
printf("更新表格\n");
}
};
// 柱状图
class histogram : public abstract_info
{
public:
virtual void update_info() override {
printf("更新柱状图\n");
}
};
// 饼图
class sector_graph : public abstract_info
{
public:
virtual void update_info() override {
printf("更新饼图\n");
}
};
// 抽象通知者
class abstract_notify
{
public:
virtual void insert_item(abstract_info *info) = 0;
virtual void remove_item(abstract_info *info, bool all = false) = 0;
virtual void notify() = 0;
virtual ~abstract_notify() {}
};
// 信息更新通知者
class info_update : public abstract_notify
{
public:
virtual void insert_item(abstract_info *info) override {
l.push_back(info);
}
virtual void remove_item(abstract_info *info, bool all = false) override {
if (all) {
l.clear();
}
else {
l.remove(info);
}
}
virtual void notify() override {
for (auto it = l.begin(); it != l.end(); it++) {
(*it)->update_info();
}
}
private:
list<abstract_info *> l;
};
}
// 可以看出观察者模式 本质上只是通过一个中间类,提供一种容器存储要更新的对象 依次更新 实现解藕 利于管理
int main(void)
{
using namespace observer_pattern;
abstract_info *f = new form;
abstract_info *h = new histogram;
abstract_info *s = new sector_graph;
abstract_notify *notify = new info_update;
notify->insert_item(s);
notify->insert_item(h);
notify->insert_item(f);
notify->notify();
notify->remove_item(h);
notify->notify();
delete s;
delete h;
delete f;
return 0;
} 哇,这是森马语言啊 Gaho2002 发表于 2020-11-16 13:48
哇,这是森马语言啊
哈哈,我也想知道。。。 namespace ,virtual, 妥妥的cpp
页:
[1]