I have a problem that involves a relatively large object hierarchy as follows:
- game has one community manager
- community manager has one network
- network has many players
- network has many friendships
- player has one strategy manager
- player has one memory
- player has one neighbourhood
- neighbourhood has many players
- strategy manager has many strategies
As you can see, the hierarchy is relatively complex and in at least one place cyclic (network has many agents having one neighbourhood which has one network). At the moment I am using a static construct method on a GameFactory
class to construct the whole hierarchy but I'm pretty sure this is the least flexible way of doing it!
In terms of building a complex hierarchy of objects what is the best pattern to use? I've read up on the Factory Method
, Abstract Factory
and Builder
patterns and I think one of the factory patterns is suitable but I don't really know how to apply it to such a complex hierarchy?
As I see it I'll need many factories for each part of the system but this will result in a collection of factory classes mirroring the model classes.
Edit: It has become clear from the discussion in suggestions given so far that I should have explained more about why I require factories to build my object hierarchies rather than allowing constructors themselves to build their dependencies.
This is because I am using dependency injection to aid in test driven development. I'm taking a mockist approach to the testing which requires the ability to inject mocks representing an object's dependencies and as such I have to avoid using new
in any constructors.
From the suggestions given so far it seems there are a number of possible ways of doing this:
- Create a secondary constructor in each class that builds any dependencies required by the object being constructed. This allows dependency injection and simple object hierarchy construction.
- Have a factory class (either a single one or a hierarchy of them depending on the type of factory pattern used) mapping to each domain class to deal with its construction.
- Use a combination of these methods where factory classes are only created when there is something that varies in the construction process (i.e., different subclasses need to be constructed under certain circumstances)
I am inclined to take the last route. What is the consensus on the best approach to take in this situation?
Edit: I'm revoking the current answer (the one by Patrick Karcher) since now that this question's focus has been clarified, none of the suggestions are complete answers.