tags:

views:

53

answers:

2

I have the following class:

class PluginLoader
{
public:
    PluginLoader(Logger&, PluginFactory&, ConflictResolver&);
    //Functions.
private:
    //Members and functions
};

Logger, PluginFactory and ConflictResolver classes are all interface classes which will be implemented in the application. I create the single PluginLoader object at top level in the main program. The Logger can be known at that level. But, PluginFactory and ConflictResolver are only used internally in the PluginLoader class. So creating their objects at top level seems ugly. What should I do? I can change the constructor if it is needed though I'd like to keep it the way it is. Any comments are welcome. Thanks.

A: 

I would make the PluginLoader class have pointers to those classes. I would forward declare the classes and I wouldn't define the classes anywhere but in the implementation files so that no one else has visibility. That is better encapsulation, plus doing that cuts down on compile time too.

I wouldn't use a raw pointer, but auto_ptr, scoped_ptr or unique_ptr should work.

If you create those objects in the constructor, or even later when first used (lazy construction) then you don't need to pass anything into the constructor and you can drop those parameters.

Edit:

From other comments I see I may have misunderstood your question. If you want to have customizable objects that implement an interface but can be anything underneath then you have to create them at the top level and pass in the interface reference/pointer, like you are doing.

I suppose that you could use a template to "pass" the class type into your object so that it can create those classes for itself. However, using templates would make the class types be fixed at compile time which may not be what you want.

Zan Lynx
So, the responsibility to create concrete objects for interfaces falls on the top level?
nakiya
@nakiya: Well, explain where else might create those objects?
Zan Lynx
@Zan Lynx: Yep, I can't see anywhere else. I wish there was a way in which the `PluginLoader` class can create the objects it uses internally itself. Perhaps by passing `MainClass` as a parameter to the `PluginLoader` constructor - that again would mean there will have to be a way to find out what to create from `MainClass`. I guess I'd rather go with this.
nakiya
A: 

My impression is that you are exposing the internal stuff in the constructor for possible customization but not the typical case. If this is correct then one thought is to make these parameters optional and create them inside if not provided.

fhj