gpt4 book ai didi

c++ - 还是观察者模式?

转载 作者:行者123 更新时间:2023-11-30 04:00:47 25 4
gpt4 key购买 nike

通常当我看到有关观察者模式的教程时,我会看到一个名为 notify 的独特方法,但我想知道。如果我有不同的方法可以在不同的时刻调用但需要在发生这种情况时通知其他方法怎么办?就像事件一样,我做错了吗?还是继续观察者模式?

#include <iostream>
#include <algorithm>
#include <vector>

class Observer
{
public:
virtual void notifyBefore() = 0;
virtual void notifyAfter() = 0;
};

class Subject
{
public:
void attachObserver(Observer * observer)
{
observers.push_back(observer);
}

void detachObserver(Observer * observer)
{
auto index = std::find(observers.begin(), observers.end(), observer);
if (index != observers.end())
{
observers.erase(index);
}
}

virtual void notifyBefore()
{
for (auto current : observers)
{
current->notifyBefore();
}
}

virtual void notifyAfter()
{
for (auto current : observers)
{
current->notifyAfter();
}
}
private:
std::vector<Observer *> observers;
};

class ConcreteObserver : public Observer
{
public:
void notifyBefore()
{
std::cout << "You called me before..." << std::endl;
}

void notifyAfter()
{
std::cout << "You called me after..." << std::endl;
}
};

class ConcreteSubject : public Subject
{
public:

};

int main()
{
auto subject = new ConcreteSubject;
subject->attachObserver(new ConcreteObserver);

subject->notifyBefore();

for (int i = 0; i < 5; ++i)
std::cout << i << std::endl;

subject->notifyAfter();
}

最佳答案

还是观察者模式?当然

关于c++ - 还是观察者模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26107461/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com