Search code examples
abstract-factory

Why use an abstract factory


Trying to figure out the difference between factory and abstract factory.

From what I understand, I would use a factory when I want to create objects with same properties but different type (for example - I want to have 10 horses, with same weight, height and age, but they should differ in name).

So I create an interface (or maybe abstract class?) that already takes care of the weight, height and age, and just feeds it with name when I want to create a new horse.

Assume I want to add colour property to the horses. Would that be a good reason to use an abstract factory? I will get 2 factories - one for black horses and one for brown horses. Does it make any sense?


Solution

  • The abstract factory pattern revolves around creating a factory that builds other factories. So you would rather use it when you have a scenario where you know you want to construct for instance horses, cows and MAYBE also pigs and sheep to follow your analogy. Given they are all farm animals, they will likely share a lot of properties and thus their factories should be similiar in some senses, so you can create a factory of factories to produce a skeleton "farm animal factory".

    From this you can now produce a horse factory, cow factory and whatever else you need.

    So basically it is abstracting the factory concept further, so that you can use a template way of creating not only objects but the factories that will produce them...