Jarrett
Jarrett

Reputation: 1778

store pointer to use for event listener registration

I have a c++ (c++11) library I'm writing (an OpenGL graphics engine).

My question revolves around good programming techniques for registering an event listener.

I have class relationships like so:

Program --has--> SceneManager --has--> ShaderManager --has-->* Shader

The Shader class allows other objects to register themselves as a ShaderBindListener, which means that whenever the shader has it's bind() method called, it will notify any listeners.

The ShaderManager Class is the one that an outside library has access to, and from which they can create new Shader objects.

Now, I want each Shader object to have the Program object as a ShaderBindListener, so that when a Shader is bound, the Program object is notified and can pass matrix data, etc to the Shader on the GPU.

My initial solution was to have the Program object pass a pointer to itself to the SceneManager, which passes the pointer to the ShaderManager, which then stores it. Whenever a new Shader is then created, the ShaderManager adds the Program as a listener.

This works just fine - but it seems - I don't know, a bit wrong in terms of design.

Maybe I'm just being pedantic - but does this seem like good design to you guys?

Upvotes: 1

Views: 135

Answers (1)

Anthony
Anthony

Reputation: 12407

There are a few options, the pros and cons for which are often debatable and depends on your style.

Singleton

If a process will only ever have one instance of Program, then you could make Program a singleton. This way, you don't need to pass the pointers around.

An intermediate object

Instead of passing the this pointer through, you could have it pass through an object which encapsulates Program and manages the event handling of it. That way, the other classes don't need to know about Program, they just need the interface for the event class.

In fact, if you aren't averse to using Boost, then they have just what you're looking for: the Signals2 library.

Upvotes: 2

Related Questions