Reputation: 17708
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.
Upvotes: 0
Views: 324
Reputation: 25707
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.
Upvotes: 0
Reputation: 1502376
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?
Upvotes: 3