简体   繁体   中英

How can I implement this with Polymorphism?

My game gui api supports 2 backends. 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. 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. 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.

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. Each of your two backends will need to override this base class and give their own implementation of handleEvent .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM