mardi 22 décembre 2020

Design pattern to limit access to a class's public members in C++

All of the code below is pseudo-code, for the sake of brevity.

Consider an event system, where have the following class:

class Event_dispatcher {
private:
    Listener_collection listeners;

public:
    void add_listener(Listener _listener) { ... }
    void remove_listener(Listener _listener) { ... }
    void post_event(Event _event) { ... }
};

I intend to have instances of Event_dispatcher in classes that are meant to send out events. However, I only want the events to be posted from inside the class, so that the user can only add or remove listeners, but never post events.
The simple solution would be to make Event_dispatcher a private member of the enclosing class, but then, I have to define add_listener and remove_listener as public members that forward the argument to the event dispatcher.
I am aware that two methods do not seem like a lot, but please bear in mind, this is just an example, I made it short on purpose. Imagine the same problem where I would have to define a significantly greater number of methods in a similar fashion.

I am trying to find out if there is a common or recommended way of solving problems like this. A solution that came to my mind would be to define an interface class like this:

class Event_dispatcher_interface {
private:
    Event_dispatcher* event_dispatcher;

public:
    void add_listener(Listener _listener) { event_dispatcher->add_listener(_listener); }
    void remove_listener(Listener _listener) { event_dispatcher->remove_listener(_listener); }
};

and make this a public member of the enclosing class. The pointer inside (*event_dispatcher) would point to the Event_dispatcher that's a private member of the enclosing class, so as to only allow for posting events from inside the class.

If there are other (better) solutions, I would appreciate any hints.

Aucun commentaire:

Enregistrer un commentaire