In a specific program I'm coding, I'm having trouble to decide whether to use function pointer or an Observer-pattern class.
There is a struct called Universe which runs n-body simulations. Occasionally there are some collision between some of its bodies, and I wanted to "listen" to these events. I came up with 2 options:
Declare a function pointer to be called when the simulation end up with a collision:
struct Universe
{
//... simulation stuff
//a "user-defined" callback when a collision occurs
void (*onCollision)(vector<Body*>& collidingList, Body& resultingMerger);
}
Define a CollisionListener class to be derived by registered "listeners" and notify about collision:
struct Universe
{
//... simulation stuff
//class to be derived
struct CollisionListener
{
//gets called when a collision occurs
virtual void onCollision(vector<Body>& collidingList, Body& resultingMerger)=0;
}
//list of registered listeners. onCollision() is called on each listener for each collision
vector<CollisionListener*> listeners;
}
Is the second option an overkill? When the number of bodies is high, there should be a lot of collisions.