I'm currently learning about design patterns. I learned about the Factory Method pattern.
This pattern means that in order to implement a factory to create objects, one should subclass the class that needs these objects, and have the subclass create them. This way the superclass only works with more abstract references instead of the concrete implementations the subclass generates, which creates a loosely coupled design.
This usually means the superclass becomes abstract
, since it's createObject()
method must be abstract
so that the subclass containing the factory method will have to implement this method.
Like any factory pattern, this pattern encapsulates the creation of the concrete object, and allows the client to work with a higher level of abstraction. But this specific pattern is built on inheritance.
What I don't understand is - Why would anybody go through all the trouble of subclassing the class that needs a factory and making it abstract
? Composition is so much better for this purpose in any way.
It makes much more sense to create an abstract class or an interface called Factory
. It would declare one method: createObject()
. We create concrete implementations of it for different purposes (WeaponFactory
, TitleFactory
..) Then, we give the client a Factory
member instance factory
. This reference is set to whatever concrete Factory
is needed at runtime, and the client can simply use factory
's createObject()
when needed (without having to know what concrete implementation factory
is holding).
I don't understand why one would go through the trouble of subclassing a class and making it abstract just for the benefit of allowing it to use a factory in a loosely-coupled manner.
The simple composition-based design I described is better in any way - I think.
Do you agree? Could you explain why anybody would use the Factory Method Pattern I described?