2

我有一个通知类,它的界面类似于以下(有一些语法问题):

template<typename ...T>
Notification
{

public:
void addObserver(std::function<void (T...)> o);
void notify(T...);
};

然后有一个作为通知中心的主机类:

class NotificationCenter
{

public:
    Notification<int, int> mPointChangedNotification;
};

最后,有一个实际的观察者来监听通知:

class Listener
{
void someFunction(int, int)
{
}

void SomeMethod(NotificationCenter &m)
{
m.mPointChangedNotification.addObserver(someFunction);
}
};

到目前为止,一切都很好。但问题是即使实际观察者也可以看到 notify 函数,而它应该只能被 NotificationCenter 类访问。如果有人可以帮助解决这个设计问题,那将非常有帮助。

提前致谢。

4

1 回答 1

3

如果您在设计访问控制策略时不需要太大的灵活性,您可以简单地制作您的NotificationCenter类模板(同样,提供私有可访问性):friendNotificationnotify()

template<typename ...T>
Notification
{
public:
    void addObserver(std::function<void (T...)> o);
private:
    friend class NotificationCenter;
    void notify(T...);
};

这样,NotificationCenter将允许调用notify(),但所有其他客户端只能访问addObserver().


如果您想允许更大的灵活性,您可以让Notification接受进一步的模板参数,并使该模板参数中指定的类型friendNotification. 然后,您可以提供notify()私有可访问性,以便其他非friend类将无法调用它:

template<typename F, typename ...T>
Notification
{
public:
    void addObserver(std::function<void (T...)> o);
private:
    friend class F;
//  ^^^^^^^^^^^^^^^
    void notify(T...);
};
于 2013-04-12T13:55:36.270 回答