【问题标题】:Still an observer pattern?还是观察者模式?
【发布时间】:2014-09-29 19:33:16
【问题描述】:

通常当我看到有关观察者模式的教程时,我会看到一种称为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++ design-patterns observer-pattern


【解决方案1】:

它仍然是观察者模式吗?确定

【讨论】:

    【解决方案2】:

    您创建了具有 2 种事件/通知类型的观察者模式。

    你可以这样写:

    void notify(Type type);
    

    其中 Type 是事件的类型(例如枚举)。

    您还可以传递其他参数来指示与事件相关的其他参数。

    void notify(Type type, std::string value);
    

    【讨论】:

    • 喜欢策略模式?这可能会有所帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-20
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多