[英]How can I implement this with Polymorphism?
My game gui api supports 2 backends. 我的游戏gui api支持2个后端。 They both work similarly and use event queues.
它们的工作方式相似,并使用事件队列。 The problem is that I do not want my API to handle the whole game's events, only peek at an event and do something, then let the game do whatever with it.
问题是我不希望我的API处理整个游戏的事件,只看一个事件然后做点什么,然后让游戏用它做任何事情。 That's why I cannot just give it the event queue.
这就是为什么我不能只给它事件队列。 My issue is that, I will have a method called handleEvent which will take in a pointer to the event, but for it to work for both this would have to be a void* but I feel like this is bad practice.
我的问题是,我将有一个名为handleEvent的方法,它将接收一个指向事件的指针,但是为了它可以工作,这必须是一个空*但我觉得这是不好的做法。 What could I do?
我能做什么? Thanks
谢谢
Create a base class for events as viewed by your handler. 为处理程序查看的事件创建基类。 Create subclasses for the events from both backends.
为两个后端的事件创建子类。 When events are raised, wrap them in the appropriate subclass.
引发事件时,将它们包装在适当的子类中。 Your handler can then take an object of the base class.
然后,您的处理程序可以获取基类的对象。
Well, this depends on a number of different factors, but I suspect you will want double-dispatch (for this particular kind of scenario), unless your event types have similar characteristics and handling behavior. 嗯,这取决于许多不同的因素,但我怀疑你会想要双重调度 (对于这种特殊情况),除非你的事件类型具有类似的特征和处理行为。 In either case, you should have a pure virtual base class representing an arbitrary event, and then you should create concrete event classes that are derived from that base class.
在这两种情况下,您都应具有一个表示任意事件的纯虚拟基类,然后应创建派生自该基类的具体事件类。 Your event handler can then accept the base type, and use the common interface for handling that event.
然后,您的事件处理程序可以接受基类型,并使用公共接口来处理该事件。 If you find yourself doing something like "if it's this type of event, then __ , else if it is that type of event do _ ", then you will probably want to use double-dispatch, which allows you to select a more specific handler for a more specific event subtype without using RTTI operations or baking-in the set of recognized event types.
如果发现自己做的事情类似“如果是这种类型的事件,则为__,否则,如果是这种类型的事件则为_ ”,则您可能需要使用双调度,这使您可以选择一个更具体的处理程序针对更特定的事件子类型,而无需使用RTTI操作或烘焙已识别的事件类型集合。
class Event {
public:
virtual void dispatch(EventHandler* handler) const = 0;
};
class EventHandler {
public:
virtual void handle(const Event* event) {
event->dispatch(this);
}
virtual void handleMouseClickEvent(const MouseClickEvent* mouseclick) {
// ...
}
};
class MouseClickEvent : public Event {
public:
virtual void dispatch(EventHandler* handler) const {
handler->handleMouseClickEvent(this);
}
};
What you do is create a base class with a virtual handleEvent
method. 您要做的是使用虚拟
handleEvent
方法创建基类。 Each of your two backends will need to override this base class and give their own implementation of handleEvent
. 您的两个后端都需要重写此基类,并提供自己的
handleEvent
实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.