观察者模式专业化 [英] Observer pattern specialisation

查看:86
本文介绍了观察者模式专业化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将Observer模式用于某些输入内容,例如:

I'm trying to use the Observer pattern for some input stuff like so:

class Observer
{
public:
    virtual void notify(Subject & o)=0;
};

class Subject
{
public:
    virtual void register(Observer * o)=0;
}

我有两个具体的主题(鼠标,键盘),它们具有特定于类的功能,我希望具体的观察者调用这些功能(getkeypress,getmousemotion等).

I have two concrete Subjects (Mouse, Keyboard), with class specific functions that I want the concrete observer to call( getkeypress, getmousemotion etc).

在不更改接口或向下转换引用的情况下,是否有任何方法可以在具体的观察者类中专门设置notify函数?我已经尝试过重载该函数,但显然不起作用,因为具体的Subjects不了解派生的Observers.

Is there any way to specialise the notify function in the concrete observer class without changing the interface, or downcasting the reference? I've tried overloading the function, but obviously that doesn't work because the concrete Subjects have no knowledge of derived Observers.

推荐答案

您通常不给观察者一个纯粹的虚拟通知功能.相反,您的主题应该重新实现一个已更改"的函数,该函数将Observer :: notify对其所有主题的调用.这样,您可以在鼠标和键盘中重新实现以调用所需的功能.

You usually don't give the observer a pure virtual notify function. Instead, your Subjects should reimplemented a "changed" function that Observer::notify calls on all its Subjects. This, you can reimplement in both Mouse and Keyboard to call the functions you want.

这确实需要更改显示的界面,因为现在还不太正确.

This does require changes to your interface as presented, because right now it's not quite right.

这篇关于观察者模式专业化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆