Imaging a simple double-dispatch event handling scheme:
It's cool. Moreover it works. However I see several issues here:
EventHandlerInterface must explicitly know all the events.
As a result of (1) handlers may have large space overhead because of subscribing for unused events.
What I want this structure to be, looks more like this:
As you can see, I want separate event types produced by different modules and I want for each module to implement only necessary event handling interfaces. I am not sure how to tie this all together. Ideally I would like to have a list of EventServices ready to accept any event.
One thing, I can think of here, is to have an inherited EventService for each EventHandlerInterface type and downcast event handlers to the certain type inside notify method. However it is not type safe and looks like an ugly idea.
Second approach, I can see, is to make EventService a template and statically check template argument to be a child of EventHandlerInterface. That would be type safe and will almost do what I want. However this way I can not store all EventServices into one list/vector as I would like to. Therefore this approach is not preferable.
Actually it feels like I am looking the wrong way but how to find the right one I don't know.
Thanks!
I am not sure the visitor pattern is the right approach for this problem. Sure it gives you a mechanism to achieve double dispatch but that's about it, and as you said it has drawbacks, e.g. the visitor (EventHandlerInterface) has to provide an overload for every different type of host (EventInterface). This creates a tight coupling and only makes sense if you add classes to the host hierarchy very infrequently.
Why not go for a solution according to the publish-subscribe pattern? It allows loose coupling and avoids the need of redundant interfaces. In brief, the publisher offers some events, to which subscribers can subscribe. When an event is triggerd, subscribers are notified and handle it. Subscribers only subscribe to events they find relevant. Different subscribers can provide different handling for the same type of event, which seems to be the purpose of double dispatch in your case.
In many languages (e.g. C#) there is special syntax for supporting this pattern easily. In C++ you need to use a library such as boost signals although there are others too. See also here for an example.
Related
Working on a cpp project, where I need something like runtime event handler. My primary goal is to keep a track of various events that takes place in a sample program and based on the events specific handlers are triggered.
These event triggering handlers/functions are not contributing anything to the global objective of the sample program, but are just keeping track over various events in the cpp sample program.
My question is it prossible to create soemthing like custom eventhandlers in cpp?
If yes, is there any tutorial for creating such custom eventhandler?
eg:
Event are like failed to enter while loop. successfully entered while loop, created object, deleted object, changed global variable etc.
The simplest form of event handler is a registered callback function pointer:
enum Events {
FailedEnteringWhileLoop ,
SuccessfullyEnteredWhileLoop ,
};
typedef void(EventHandler*)(Events);
void MyEventHandler(Events ev) {
switch(ev) {
case FailedEnteringWhileLoop:
// Do something
break;
case SuccessfullyEnteredWhileLoop:
// Do something
break;
}
}
EventHandler evh = MyEventHandler;
bool whileLoopEntered = false;
while(condition) {
if(!whileLoopEntered) {
whileLoopEntered = true;
(*evh)(SuccessfullyEnteredWhileLoop);
}
}
if(!whileLoopEntered) {
(*evh)(FailedEnteringWhileLoop);
}
I am looking for events like failed to enter while loop. successfully
entered while loop, created object, deleted object, changed global
variable etc.
The C++ language itself does not track these kinds of things as "events". Generally speaking it doesn't provide hooks into any of the various fundamental activities that happen across code.
So to do what you're asking for requires building an infrastructure yourself and working it into your code in various ways. (Or finding someone else who has done the same sort of work already and made it available. Although you still would have to integrate it into your code.)
To give some idea of what might have to be done:
For creating and deleting objects you can override the new and delete operators. But that doesn't cover stack/local/etc objects. Otherwise you could wedge something the constructors and destructors of every class you want to track, or even have all of them derive from a common base class which encapsulates the tracking.
For changes to a variable, you would have to wrap that variable in a container which only exposes the ability to change it through member functions. Then those could be coded to raise events.
For entering loops... You're out of luck because a loop isn't an entity that can be extended or hooked. You literally have to put some kind of call at every loop you want to track.
As for the rest of the infrastructure, you would probably end up doing something like having all of those various "events" call to some kind of global logging object. If you need different things catch different events over the course of a program, then you might also need to build a way of registering and de-registering listeners (the listeners themselves being based on an interface to derive from or std::function or whatever suits your use case).
But in the end since there isn't an out-of-the-box way provided by the language, you might want to re-consider what you really want and what you hope to achieve with it. In fact you might be better off asking your question in terms how to accomplish the end goal you wanted this for rather than how to do this "event" system.
I'd like to write a nested handler for consumption of json using rapidjson.
I've modeled my basic handler along the lines of the official simplereader example. This is fine for flat structures, but now I need to expand the parsing to nested objects as well.
The way I see it, I can either
have a central handler that keeps track of various domain objects to create and subsequent parse values into, or
I can change handler while parsing
Technically, I know how to do 1., but 2. seems like a neater solution, if possible.
Is it possible to change handlers mid-stream? Is there a best practice for doing this?
Thanks!
You can delegate the events to other handlers. This is often done by:
Applying the State Pattern internally in your custom handler. So that the handler can delegate the events to the current state object via polymorphism (a.k.a. virtual functions).
Using switch-case to do the delegation with an enum.
The first one has advantage if you need to deal with recursive structure. You can push the pointers of state objects in a stack.
Using C++ & MFC I've created a class which makes it easier to add drag/drop functionality to a CWnd object. There is nothing special about it really. Currently it is used like so:
Create CDropListener object
Call a method on the CDropListener object saying which file extension you want it to react to and a function pointer of what to call when a file is dropped
Register this with the CWnd object
Delete the CDropListener object when the window is destroyed
Repeat all of the above steps if you want different file extensions for a different CWnd
It is a bit cumbersome having to create a class member variable for each listener, and I was just wondering which design pattern would be more suitable for this. I only need the member objects so that I can delete them at the end. I thought I could just use an array to store them in and it would simplify it a bit, but I also thought there might be a better way where you can just call a static function similar to DropListener::RegisterListener(CWnd* wnd, CString& extension, void(*callback) callback) and it handles all of the creating / registering / deleting for you.
I'm not familiar with MFC but from an OO point of view your design can be improved.
First identify what aspects of your requirements are most likely to change and then identify what the interfaces needed to isolate those changes are:
Changes:
The thing you want to listen for (the event)
The action you want to take (the callback)
Interfaces:
The mechanism of adding a callback related to an event to the event notifier
The mechanism of calling the callback from the notifier
So you need an Event interface, a Callback interface, and a Notifier interface.
In C++ there is a handy thing called std::function<T> where T is any callable type (a pointer to a function, a functor, a lambda). So you should probably use that for encapsulating your callbacks to give your user more freedom.
Then how may event types do you want to support? This will tell you whether you need to support different Event objects as well as how your registration will look:
// For example if you support just `Drop` events:
void addDropListener(std::function<T> callback);
// If you support many events:
void addListener(Event::Type evType, std::function<T> callback);
Once you have answered that you need to decide what a "callback" looks like (T in the above examples). This could return a value (if you want success verification) or throw a particular exception type (make sure to document the contract). Then ask if you want a copy of the event that was fired (usually you would). Assuming you are happy to only be notified of errors via exceptions then you can typedef the expected std::function like this:
typedef std::function<void (const Event&)> EventCallback;
I recommend then that your Notifier implementer use a std::vector<EventCallback> or std::map<Event::Type, std:vector<EventCallback>. The first one is useful if you want to only support one event type or to call all listeners for all events. The second is handy when you want to only notify listeners of certain types of event.
In any case if you are finding that you need to change your class code to accommodate minor changes to behaviour then you need some refactoring.
Hope that helped. :)
I'm considering different approaches to implementing events in a C++ application. There's a suggestion to implement a centralized event dispatch, via a notification center. An alternative would be for sources and targets of the events to communicate directly. I'm having reservations about the notification center approach, however. I'll outline both approaches as I see them (I could well be misunderstanding something about them, I've never implemented event handling before).
a) Direct communication. Events are a part of their source's interface. Objects interested in the event must somehow get a hold of an instance of the source class and subscribe to its event(s):
struct Source
{
Event</*some_args_here*/> InterestingEventA;
Event</*some_other_args_here*/> InterestingEventB;
};
class Target
{
public:
void Subscribe(Source& s)
{
s.InterestingEventA += CreateDelegate(&MyHandlerFunction, this);
}
private:
void MyHandlerFunction(/*args*/) { /*whatever*/ }
};
(From what I understand, boost::signals, Qt signals/slots and .NET events all work like this, but I could be wrong.)
b) Notification center. Events aren't visible in their source's interface. All events go to some notification center, probably implemented as a singleton (any advice on avoiding this would be appreciated), as they are fired. Target objects don't have to know anything about the sources; they subscribe to certain event types by accessing the notification center. Once the notification center receives a new event, it notifies all its subscribers interested in that particular event.
class NotificationCenter
{
public:
NotificationCenter& Instance();
void Subscribe(IEvent& event, IEventTarget& target);
void Unsubscribe(IEvent& event, IEventTarget& target);
void FireEvent(IEvent& event);
};
class Source
{
void SomePrivateFunc()
{
// ...
InterestingEventA event(/* some args here*/);
NotificationCenter::Instance().FireEvent(event);
// ...
}
};
class Target : public IEventTarget
{
public:
Target()
{
NotificationCenter::Instance().Subscribe(InterestingEventA(), *this);
}
void OnEvent(IEvent& event) override {/**/}
};
(I took the term "Notification center" from Poco, which, as far as I understand, implements both approaches).
I can see some pros to this approach; it will be easier for the targets to create their subscriptions because they wouldn't need access to the sources. Also, there wouldn't be any lifetime management problems: unlike sources, the notification center will always outlive the targets, so they targets always unsubscribe in their destructors without worrying whether the source still exists (that's a major con I can see in the direct communication). However, I am afraid that this approach could lead to unmaintainable code, because:
All sorts of events, probably completely unrelated to each other, would go to this one big sink.
The most obvious way of implementing the notification center is as a singleton, so it will be hard to track who and when modifies the subscribers' list.
Events aren't visible in any interface, so there is no way to see whether a particular event belongs to any source at all.
As a result of these cons, I'm afraid that as the application grows it would become very difficult to track connections between objects (I'm imagining problems trying to understand why some particular event doesn't fire, for example).
I'm looking for advice regarding the pros and cons of the "notification center" approach. Is it maintainable? Does it fit every sort of applications? Maybe there are ways to improve the implementation? Comparison between the two approaches I described, as well as any other event handling suggestions, are most welcome.
These approaches are orthogonal. Direct communication should be used when the events are exchanged between specific objects. The notification center approach should only be used for broadcast events, e.g. when you want to process all events of a given type regardless of their source, or when you want to send an event to some set of objects which you don't know in advance.
To avoid singletons, reuse the code for direct communication and subscribe the notification center object to all events you want to process in this way. To keep things manageable, you would do this in the emitting objects.
The lifetime-related problems with direct communication are usually solved by requiring that every class that subscribes to any events must be derived from a specific base class; in Boost.Signals, this class is called trackable. The equivalent of your CreateDelegate function stores the information about subscriptions for the given object in data member within trackable. On destruction of trackable, all subscriptions are cancelled by calling the matching Unsubscribe functions. Note that this is not thread-safe, because the destructor of trackable is called only after the derived class destructor finishes - there is a period where a partially destroyed object can still receive events.
I will focus on pros and cons of the "NotificationCenter" solution as required by the question (though I'd call it DataBus, Dispatcher or Publisher/Subscriber, instead).
Pros:
High decoupling of the classes
The Subscriber of an event doesn't need to know the source of the event
Concurrency management is simplified if you use an asynchronous NotificationCenter (you can avoid multithreading by using the NotificationCenter as a scheduler of cpu time).
An event driven architecture is higly testable / observable
Cons:
The interface is implicit (i.e. the interface of a class does not expose the events)
The partitioning of the application is critical, in order to avoid duplication of the state in the classes
Reusability in another application becomes harder (when you want to reuse a class in another application, it brings with itself the NotificationCenter)
It's difficult to insert a new elaboration in the flow of events from input to output (i.e.: if class A emits event E and class B registers for notifications of E, you cannot insert a class C "between" A and B to change the content of E let's say to do some kind of elaboration on it)
The NotificationCenter must manage client's errors (i.e. the NotificationCenter should provide an exception handler to catch the exeptions thrown in the event handlers).
In addition, I'd like to point out that it's not indispensable that the NotificationCenter be a singleton. In fact you can have multiple instances of NotificationCenter, each managing different category of events (e.g. in an embedded system you can have a NotificationCenter for the low level hardware events and another for the high level logic).
We should limited the NotificationCenter design, it has a lot of cons for code maintain.
It hidden the object relation ship into the implementation, you cannot
get clue from caller code, who actually will explicit bind the observer and target
object in Direct communication.
You can not see the even interface from the header, you need to look
into implementation.
You have bind your business logical with the notification center, you cannot easily unit-test the business component and reuse it in other project.
The benifit of NotificationCenter is that you doesn't need to know the event source, so you should only use NotificationCenter when there is multiple event source for same event, or even source number will change.
For example, in Windows platform you want to listen all windows size changed event, but at the same time the new window can be created.
Need some help in sorting out design options for simulation framework in C++ (no C++11).
The user creates an "event dispatcher" and registers interest (using "watchers") in occurrence of "events". The dispatcher internally holds "event sources" which are used to detect event activation and manage notifications to watchers. There's a 1:1:1 mapping between watcher, event and event source classes.
I'd like to extend the system with
ability to register any sub-set of event watchers only in dispatcher (request unsupported notification will fail)
alternative implementations for event sources (e.g., one or multiple watchers per event)
extended event types (i.e., inheritance). Watcher and Source can handle sub-classes as if they're the base type, albeit with reduced functionality.
user defined event, event source and event watcher. For completely new events
I've considered using "event type identifiers" (either strings or Base.Derived notation), it works but doesn't feel correct (e.g., type safety relies on runtime integers, inheritance is limited, too many type casts...)
Would appreciate suggestions for code structure and mechanisms.
This is exactly the right situation to use dynamic_cast. It's only needed in one place.
All events inherit from a single base class, and all event handlers inherit from a (different) single base class. This makes all event sources and dispatchers uniform. Events are checked and filtered by the handlers in the base class.
This is a rough 10-minute sketch of what the overall structure could look like. There are no event sources in the sketch since it's not entirely clear to me what they should look like. I just fire events from main().