views:

209

answers:

2

I have an application which spawns a lot of child objects and each of them works with some global application objects e.g. registers itself in the global application registry, updates application statistics etc.

How should application transfer the ability to access those global objects to the children? Should every child inherit from static CRegistry and CStatistics or should application pass Registry and Statistics to child at the moment of creation?

Thanks.

+3  A: 

It would seem very odd to inherit from CRegistry - the child objects aren't just specialized registries, are they? Their interaction with the registry is just to register themselves and then be found within the registry, I'd imagine. Ditto statistics.

It certainly sounds to me like the registry and statistics should just be passed in as appropriate (e.g. into the constructor). You may well not even need to keep the registry as a member variable, if the object just needs to register and then be found later.

If this really is a single, global registry then it might be a good time to use the singleton pattern - although that tends to make testing harder, in my experience.

Alternatively, could whatever's creating the objects register them? Should it really be the child object's job?

Jon Skeet
I myself think I should not use inheritance in this case. I'm switching from C to C++ and verifying my understanding of inheritance.
Jack
Just remember, when something is inheriting it's an "is-a" relationship not a "has-a"
Sekhat
If the child object should always be registered (as seems to be indicated) then yes it should be it's job. If it doesn't always need to be registered, then it should be the job of the creator.
workmad3
A: 

No, they certainly shouldn't be inheriting from the registry. Containing a registry object in each one also seems a bit overkill, and certainly means a lot of duplicated code.

I'd probably go for the mixin approach personally. Create a class along the lines of MRegistryObjectMixin, which encapsulates the process of registering (and deregistering) and then inherit (possibly privately so you have 'is-implemented-in-terms-of', rather than 'is-a' semantics) that into all objects that need to be registered. Take care when designing your inheritance tree so that you avoid the dreaded 'Diamond of Death' as well.

workmad3