I am programming a game. In this game I have 3 stages. In the first stage, there is a static goal and a static shooter in the game. In the second stage, the goal will move. And in the third one both are moving.
I want to use abstract factory to create objects of same family.
I want to know which of the following designs is right:
With 2 factories:
With 3 factories:
I just don’t know whether I should make concrete factories in the same count of families at the right hand or according to my problem?
For example, in the scenario, I have two families of objects (Products). First family is Gun and the second is Goal. But I have 3 stages that I have explained above. Is it right to have 2 factories because of the count of families of products or to have 3 families according to the stages?
6
To be honest, I’d probably take a different approach entirely. I’d build 4 factories, one for each object type. I’d then create a new Level class that contains one instance of a GunFactory and one of a GoalFactory, and I would create 3 instances of Level (probably stored in a List) each having the appropriate combination of factory.
There are two reasons for this, one theoretical and one practical. On a theoretical level, it is not at all clear that the responsibilities “create a gun” and “create a goal” are part of the same responsibility, so the Single Responsibility Pattern states that we should avoid having a single object that doesboth. The Level object on the other hand does have one clear responsibility: “hold together all of the information and behavior necessary to initialize a level of the game”.
The second, more practical aspect, is that this lets you add new levels more easily than either of your original suggestions. Say you want to add a fourth level that uses a different combination of gun and goal again; in your first design you would have to change your existing initialization code to pick a different set of factories, in the second you’d have to create a new subclass of your abstract factory class, whereas with my suggestion you’d just add a new Level instance to the list, a single line change. (This could also be phrased theoretically as “the design is more compliant with the open/closed principle when levels need to be added”, but I prefer the practical emphasis here).
3