Factory Method Design Pattern – Benefits Over Direct Class Calls

design-patterns

From the "Gang of Four" design patterns, there's the Factory method:

class Factory(product)
  case product
  when a
    new A
  when b
    new B
  when c
    new C
end

new Factory(a)

Why is this more useful than having three classes, a, b, and c and calling them individually?

Best Answer

Because your example is not complicated enough. For such a simple scenario it doesn't even make sense to use an advanced pattern.

But if you have to know more than the product to construct A, B or C, and you can't have direct access to that knowledge, then it is useful. Then you are using the factory to act as a knowledge center for producing needed objects.

Maybe those objects need a reference to some object X, which the factory can provide, but your code in the place where you want to construct A, B or C can't or shouldn't have access to X. Maybe when you have X you create A and B but if you have Y type then you create C.

Also consider that some objects might need 20 dependencies to create; what then? Going to hunt for those dependencies in a place where they should not be accessible might be problematic.