Notification Center in C++ - c++

After programming for sometime with the iOS and Mac objective C frameworks, I have come to love the generic notification pattern implemented by the NSNotificationCenter and NSNotification classes. Coming back to C++, which has always been my language of choice for most things, I find myself trying to replicate this pattern and believe there should really already be a generic implementation of similar C++ classes offering support for it out there.
It does seem like the pattern is somewhat more difficult to implement in C++ than Objective C because of the more dynamic nature of the later, but it seems far from impossible. I've looked through the boost libraries as they are generally awesome and was sad not to find my luck there. Although the boost::bind, boost::lamda, boost::function seem like they do most of the work. Have I missed something obvious? Is there anything already existing out there that would allow me to easily replicate NSNotification/NSNotificationCenter behaviour?

In theory you could create a class that has a vector of function pointers to call when a certain notification is called - A class that has a dictionary where the objects are the vectors of functions to call when a notification is pushed

In addition to the boost packages mentioned in other answers, another option is poco::NotificationCenter.
This implementation is closer to the Cocoa notification framework, as specifically discussed on Poco's documentation:
The NotificationCenter class is basically a C++ implementation of the
NSNotificationCenter class found in Apple's Cocoa (or OpenStep).

Following #anno's recommendation to look at boot::signal, it does after examination seem like a possible option although it is, as expected, not as straight-forward as the objective C solutions. Looking through the boost::signal tutorial, I thought I would go through the most relevant aspects for the problem at hand.
To create notification senders:
Consider a simple news delivery service, where clients connect to a news provider that then sends news to all connected clients as information arrives. The news delivery service may be constructed like this:
class NewsItem { /* ... */ };
boost::signal<void (const NewsItem&)> deliverNews;
The objective of deliverNews is to inform observers that a NewsItem has been generated.
Observers can be added as follows (using the boost::bind library):
Clients that wish to receive news updates need only connect a function object that can receive news items to the deliverNews signal. For instance, we may have a special message area in our application specifically for news, e.g.,:
struct NewsMessageArea : public MessageArea
{
public:
// ...
void displayNews(const NewsItem& news) const
{
messageText = news.text();
update();
}
};
// ...
NewsMessageArea newsMessageArea = new NewsMessageArea(/* ... */);
// ...
deliverNews.connect(boost::bind(&NewsMessageArea::displayNews, newsMessageArea, _1));
To address the problem of removing observers which have been deallocated from the list, boost::signal offers the following solution
However, what if the user closes the news message area, destroying the
newsMessageArea object that deliverNews knows about? Most likely, a
segmentation fault will occur. However, with Boost.Signals one need
only make NewsMessageArea trackable, and the slot involving
newsMessageArea will be disconnected when newsMessageArea is
destroyed. The NewsMessageArea class is made trackable by deriving
publicly from the boost::signals::trackable class, e.g.:
struct NewsMessageArea : public MessageArea, public boost::signals::trackable
{
// ...
};
At this time there is a significant limitation to the use of trackable
objects in making slot connections: function objects built using
Boost.Bind are understood, such that pointers or references to
trackable objects passed to boost::bind will be found and tracked.

Related

How many listeners are too many observer pattern?

My class were inheriting from two Listeners already. And I need to add one more listener. It became something like below:
class DatabaseManager : public DatabaseChangeListener,
public PropertyChangeListener,
public RenumberListener
Should I avoid too many observers? Even though listeners are abstract classes it bothers me a bit that I am using multiple inheritance. I am curious has any one had experienced something like; because too many observers code became complex and buggy ?
The major signs of smell here are the fact that your class is called DatabaseManager (sounds like a god-object), and also the specialized tone that the interfaces have to them (e.g.RenumberListener).
There's nothing inherently wrong with supporting several event hooks, nor with multiple inheritance in and of itself. You might just need to group some interfaces into one clear one that describes what your class does, its basic right to exist, who uses it, and for what purpose.
Also note, implementing an interface is a type of functionality directed at the consumers of the class. If there's no need for generic interfaces, it's better not to have them, for otherwise you might find yourself with an interface per member function in the system at one extreme, and at the other, no clear guideline on what makes an interface and what doesn't.
If you want to reduce the number of classes, you can try to abstract away the different type of messages your listening to by creating a basic listener interface, e.g.,
virtual void onEvent(Subject * subject, Message * message) = 0;
Then you register your DatabaseManager for different type of events? This way you can still use single inheritance. I know that system like Qt etc use this for dispatching events.
But as far as I know, if your base classes (DatabaseChangeListener, PropertyChangeListener and RenumberListener) are pure abstract, you will not encounter problems with multiple inheritance.
Don't use inheritance. Implement one listener interface and use onEvent method to handle it passing event to different handlers. Subscribe your object on different event types. This way you can easily change any events and handlers without changing your DatabaseManager. Even new events doesn't require much from DatabaseManager.
Consider using something like Chain of Responsibility to make your manager class fully undependable of event types. It could use just a chain of IHandler objects, which can be injected in constructor

Avoid cyclic references

I'm building a small game with SDL. I've a class GameObject which is the main class for representing objects in my game. The different behaviors are solved my components you can inject from the outside:
#include "Input.h"
class GameObject
{
public:
void setInput(Input* input)
{
input->setGameObject(this);
this->input = input;
}
}
class GameObject; // cannot #include "GameObject.h"
class Input
{
private:
GameObject* object;
public:
void update(float elapsedTime)
{
// do fancy stuff on the GameObject object
}
void setGameObject(GameObject* object)
{
this->object = object;
}
}
The Input class has to work on the GameObject instance. I have a cyclic reference now which is not a good idea I guess?
Edit: I adjusted my example to make it clearer. I have some of these components like the Input class and I've to use this class GameObject; statement since I cannot include the header file.
So if I understood it correctly I've a cyclic reference!? To solve that I would have to use an interface and add this to setGameObject(InputInterface* object). But I cannot predict what functions/member are needed for access of the GameObject because there are different components used (e.g. PlayerInput, DemoInput, AiInput, ...).
It seems you're using raw pointers (personally I think this is a bad idea), so I see no problem in having this cyclic reference, just remember to check for null.
If you were using smarter pointer types, in this case you would use a strong reference in one direction (the one that "contains" the other) and a weak reference in the other (the one that only needs a way to communicate).
For example, your game object probably owns the input mechanism; but the input mechanism just needs a way to communicate the input to the game object.
std::weak_ptr is used to break circular references of std::shared_ptr.
See: http://en.cppreference.com/w/cpp/memory/weak_ptr
Also, check if your input really needs a hold on the whole game object, or just some object that has certain interface. In that case, event mechanisms or the delegate pattern could help you remove some hard dependencies.
Cyclic references or two-sided reactivity is not uncommon.
For example, say we have a client/server relationship. Based on changes on the client or the server for, say, a webapp, the server can decide to update the client, or the client can forward an activity or action that the user has taken that requires a client's response. Either way, both might have a reference to the same data or to each other, which requires "references..." or do they? Sometimes, it can be more helpful to decouple the references from the interface to modify the data pointed to by the references.
The general response for this, much like web communications, is asynchronous I/O or message passing, and this is not an unusual pattern in even a game--often times, single-player games can make use of the message-passing model (think SimCity's GlassBox simulation with "agents" or MMORPGs with actual networking messages/packets).
If you're concerned about "coupling," perhaps you should consider various async techniques to prevent classes from having built-in callbacks to other modules that require their definitions; callbacks/reactor functions are a very common occurrence--Boost.Signals2 has a nice example of how this might be used, as well as std::async, I believe. Another option is to simply abstract everything with message passing, much like peer-to-peer networking, and encapsulate each module of your engine with message-passing/receiving modules. This would also make diagnostics easier to implement, provided an external module could "peek" at the metadata of messages.

C++ Java Handler equivilent

I'm coming from a Java/C# background and am new to C++. I am writing a library and am trying to accomplish the same functionality as a Handler does in Java. My scenario is as follows:
I am building a WinRT library that a user will put into his mobile/desktop app. At some point, after some network communication happens, a piece of data will come in that I want to pass along to the user. In Java, I declare a public static Handler (but do not initialize it) that the user can initialize. When the data comes in, I send a message through that Handler, and the end user's declaration within their app gets called, receiving the message and grabbing the data from it.
I can't seem to find a way to do the same in C++. I have looked at all kinds of posts/documentation on delegates/function pointers, utilizing the mighty Google with keywords like "callback", "handler", and "delegate". I think I have a half-formed understanding that it work differently in C++, but nothing is bearing fruit.
Could anyone kindly point me in the right direction?
Pretty much the same as you'd do it in Java. In your library, define a pure virtual class (more-or-less analogous with Java interface) of the handler.
class somethinghandler
{
public:
virtual void somethinghappened(<stuff that happened>) = 0;
}
And define and implement a class to watch for the event and call the function defined in the handler. This class contains a pointer, or list of pointers, objects installed by the client and methods to add and remove clients. If possible, don't use pointers at all let something do all of the containing. Life is cleaner that way. If you can't, guard the pointers with shared_ptr so that they cannot easily be destroyed before they are removed from the watcher.
class somethingwatcher
{
public:
bool addClient(std::shared_ptr<somethinghandler> clientToAdd);
bool removeClient(std::shared_ptr<somethinghandler> clientToRemove);
void applogic();
private:
std::shared_ptr<somethinghandler> client;
// or std::vector<std::shared_ptr<somethinghandler>> clients;
}
Finally, somewhere in somethingwatcher's application logic you detect something happened and call the client.
void somethingwatcher::applogic()
{
// do stuff
if(<something happened>)
{
// or iterate through the list of clients and doing for each:
if (client != nullptr)
{
client->somethinghappened(<stuff that happened>);
}
}
}
The library doesn't need to know anything about the client other than it exists and implements the somethinghappened function defined in somethinghandler. So long as you have a valid pointer, magic happens. Well, not really but this isn't the right place to go into how that "magic" works.
Outside the library in Client Land...
The client code defines and implements a class that implements somethinghandler to receive calls to somethinghappened.
class somethingclient: public somethinghandler
{
public:
void somethinghappened(<stuff that happened>);
\\ handles something happening.
}
Assuming the client code has instantiated a somethingwatcher named watcher, then an initialization routine creates and adds a somethingclient to watcher.
std::shared_ptr<somethinghandler> handler = std::make_shared<somethingclient>(constructor arguments);
watcher.addClient(handler);

C++ Callbacks? Should I use Member Func Pointers/Delegates/Events?

I am entering a realm that is new to me, but basically I need to implement callbacks in C++. I am designing a toolkit for myself to use to simplify my life. Basically it is a .dll plugin that will be exposing a lot of functions to my other .dll plugins.
One of these functions is HookEvent(const char *event_name, void *callback) which will allow me to hook different events that get fired. Here would be an example...
Example_Plugin1.dll does HookEvent("player_spawn", &Plugin1::Event_PlayerSpawn);
Example_Plugin2.dll does HookEvent("player_spawn", &Plugin2::Event_PlayerSpawn);
I need to figure out the best (and preferably easiest) method of setting up a callbacks system that will work well for this. I have been reading up on C++ callbacks for a few hours now, and found quite a few different approaches.
I assume the easiest thing to do would be make a template, and use typedef bool (ClassName::*EventHookCallback)(IGameEvent, bool); After that, I am a bit foggy.
I also read that Delegates or a .NET style events system are other possible approaches. I am already somewhat confused, so I don't want to confuse myself more, but figured it was worth asking.
Here is a link to the C++ .NET style events system I was reading about.
http://cratonica.wordpress.com/2010/02/19/implementing-c-net-events-in-c/
So what do you guys suggest? Any tips as far as implementing it would be most appreciated.
If you want generalized event firing Boost.Signals2 might be applicable.
The Boost.Signals2 library is an
implementation of a managed signals
and slots system. Signals represent
callbacks with multiple targets, and
are also called publishers or events
in similar systems. Signals are
connected to some set of slots, which
are callback receivers (also called
event targets or subscribers), which
are called when the signal is
"emitted."
Even if you don't need this level of flexibility you should be able to simplify the function binding in your code using Boost.Bind, or the C++0x equivalents.
EDIT:
There's an excellent discussion from Herb Sutter of the issues you could face here. You could use this for guidance if you decide you don't need the full Boost feature set, and so roll your own.
How about using Qt Signal and Slot? It does what callbacks do but without the messiness of making anything not part of your callback parameters global.
Boost.Signals would be my choice, combined with things like boost::bind and Boost.Function.
I would use an abstract base class as a plugin interface. (And in fact, I have used a pattern like the one below before.)
Library, PluginIfc.h:
class PluginIfc {
public:
virtual ~PluginIfc() = 0;
virtual bool EventCallback(const char* event_name, IGameEvent, bool) = 0;
};
// For Windows, add dllexport/dllimport magic to this declaration.
// This is the only symbol you will look up from the plugin and invoke.
extern "C" PluginIfc* GetPlugin();
Plugin:
#include <PluginIfc.h>
class Plugin1 : public PluginIfc {
public:
virtual bool EventCallback(const char* event_name, IGameEvent, bool);
Plugin1& get() { return the_plugin_obj; }
bool Event_PlayerSpawn(IGameEvent, bool);
// ...
private:
std::vector<std::string> _some_member;
static Plugin1 the_plugin_obj; // constructed when plugin loaded
};
Plugin1 Plugin1::the_plugin_obj;
PluginIfc* GetPlugin() { return &Plugin1::get(); }
This way, your plugin classes can easily have members, and C++'s virtual call mechanism takes care of giving you a good this pointer in EventCallback.
It may be tempting to make a virtual method per event type, say just make Event_PlayerSpawn and similar methods virtual. But then whenever you want to add an event type, if this means changing class PluginIfc, your old compiled plugins are no longer compatible. So it's safer to use a string event identifier (for extensibility) and have the main callback sort events off to more specific methods.
The major drawback here (as compared to a signal-slot type implementation) is that all callbacks must take the same set of arguments. But your question sounded like that would be adequate. And it's often possible to work within that limitation by making sure the set of arguments is very flexible, using strings to be parsed or Any-style objects.
Sounds like you might be interested in how to build your own plugin framework. The problems you'll encounter are likely the same. Have a look at this nice Dr Dobbs article Building Your Own Plugin Framework.
Hope this helps!
Implementing your own callback system is non-trivial.
My understanding is that your aim is to map event types to specific callback functions.
E.g. if "player_spawn" event is risen the &Plugin1::Event_PlayerSpawn will be called.
So what you should do is the following:
1) Define all the events of interest. Make them as generic as possible. They can
encapsulate any information you need
2) Create a Registrar. I.e. a class that all modules register their interest for specific
methods. E.g. Registrar.register(player_spawn,this,Event_PlayerSpawn);
3) Registrar has a queue of all subscribers.
4) You can also have a uniform interface for the modules. I.e. all module implement a specific function but based on event's data can do different things
5) When an event occurs, all the subscribers interested for the specific event get notified by calling the appropriate function
6)Subscriber can de-register when ever is need
Hope this helps.

How would you implement Erlang-like send and receive in C++?

Actually, this question seems to have two parts:
How to implement pattern matching?
How to implement send and receive (i.e. the Actor model)?
For the pattern matching part, I've been looking into various projects like App and Prop. These look pretty nice, but couldn't get them to work on a recent version (4.x) of g++. The Felix language also seems to support pattern matching pretty well, but isn't really C++.
As for the Actor model, there are existing implementations like ACT++ and Theron, but I couldn't find anything but papers on the former, and the latter is single-threaded only [see answers].
Personally, I've implemented actors using threading and a thread-safe message queue. Messages are hash-like structures, and used these together with a number of preprocessor macros to implemented simple pattern matching.
Right now, I can use the following code to send a message:
(new Message(this))
->set("foo", "bar")
->set("baz", 123)
->send(recipient);
And the following to do simple pattern matching (qDebug and qPrintable are Qt-specific):
receive_and_match(m)
match_key("foo") { qDebug("foo: %s", qPrintable(m->value("foo").toString())); }
or_match_key("baz") { qDebug("baz: %d", m->value("baz").toInt()); }
or_match_ignore
end_receive
However, this looks a bit hackish to me, and isn't very robust.
How would you do it? Did I miss any existing work?
As for the Actor model, there are
existing implementations like ACT++
and Theron, but I couldn't find
anything but papers on the former, and
the latter is single-threaded only.
As the author of Theron, I was curious why you believe it's single-threaded?
Personally, I've implemented actors
using threading and a thread-safe
message queue
That's how Theron is implemented.. :-)
Ash
One of the important things about erlang is how the features are used to make robust systems.
The send/recieve model is no-sharing, and explicitly copying.
The processes themselves are lightweight threads.
If you did desire the robust properties of the erlang model, you would be best to use real processes and IPC rather than threads.
If you want robust message passing though you may end up wanting to serialize and deserialise the contents. Especially with type safety.
Pattern matching in C++ isn't always pretty but there will be a good pattern for this - you will end up creating a dispatcher object that uses some form of polymorphism to get what you want.
Although if you are not careful you end up with xml over pipes :)
Really, if you want the erlang model you really want to use erlang. If there are slow bits, I'm sure you can augment your program using a foreign function internet.
The problem about re-implementing parts, is you won't get a good cohesive library and solution. The solutions you have already don't look much like C++ anymore.
I'm currently implementing an actor library for C++ called "acedia" (there's nothing yet about it on google) that uses "type matching". The library is a project for my master thesis and you can send any kind of data to an actor with it.
A small snippet:
recipient.send(23, 12.23f);
And on the recipient side you can either analyze the received message like this:
Message msg = receive();
if (msg.match<int, float>() { ... }
... or you can define a rule set that invokes a function or method for you:
void doSomething(int, float);
InvokeRuleSet irs;
irs.add(on<int, float>() >> doSomething);
receiveAndInvoke(irs);
It's also possible to match both on type and on value:
Message msg = receive();
if (msg.match<int, float>(42, WILDCARD) { ... }
else if (msg.match<int, float>() { ... }
The constant "WILDCARD" means, that any value will be acceptet. Pass no arguments is equal set all arguments to "WILDCARD"; meaning that you only want to match the types.
This is certainly a small snippet. Also you can use "case classes" like in Scala. They are comparable to "atomics" in erlang. Here is a more detailed example:
ACEDIA_DECLARE_CASE_CLASS(ShutdownMessage)
ACEDIA_DECLARE_CASE_CLASS(Event1)
ACEDIA_DECLARE_CASE_CLASS(Event2)
To react to the defined case classes you can write an actor like this:
class SomeActor : public Actor
{
void shutdown() { done = true; }
void handleEvent1();
void handleEvent1();
public:
SomeActor() : done(false) { }
virtual void act()
{
InvokeRuleSet irs;
irs
.add(on<ShutdownMessage>() >> method(&SomeActor::shutdown))
.add(on<Event1>() >> method(&SomeActor::handleEvent1))
.add(on<Event2>() >> method(&SomeActor::handleEvent2))
;
while (!done) receiveAndInvoke(irs);
}
};
To create a new actor and start it, all you have to write is:
Acedia::spawn<SomeActor>();
Although the library not even reached beta stadium the shown snippets work and i have a first application running on it. One major goal of the library is to support distributed programming (also across a network).
Your question is a while ago, but if you're interested in it: let me know! :)
You can mimic the behavior using Qt's signal/slot mechanism, especially since Qt's signal/slot supports multithread.
I would definitely be interested in looking at your "acedia" library and would love to help in any way that I could. Erlang has some wonderful constructs and C++ could definitely benefit from such a library.
Today I hostet the library at sourceforge: https://sourceforge.net/projects/acedia/
As I said before it's an early release. But feel free to critique it!
Today, if you want erlang style robust actors in C++, and pattern matching,
maybe Rust is the answer.
Of course this wasn't around publically when the OP asked ~5years ago, and as of april 2014 it still isn't v1.0 yet - but its been progressing very well and is definitely stabilizing, enough of the language core is stable I think.
And ok its not C++, but it has the same approach to memory management as C++, except that it supports lightweight tasks with no shared memory by default (then provides controlled library features for sharing - "Arc");
It can directly call (and directly expose) 'extern C' functions. You can't share templated library headers with C++ - but you can write generics that mimick C++ collection classes (and vica versa) to pass references to data-structures across.