Abstract Factory

A factory of factories.

Sometimes referred as factory of factories, this pattern is useful only when you have bunch of factories which are related, as you might guess you have factories only when you want to create bunch of related classes, hence the name factory of factories.

This pattern is similar to that of factories pattern except that in factory pattern factory is responsible for creating the concrete objects where as in here the abstract factory delegates it to the relevant factory to create objects.

Lets consider we have to perform a cohesive task of drawing. For our understanding purpose lets imagine our module divides the diagram into shapes,and colours to be filled in shape.

Similar to the UML diagram shown.

One of the main advantage here, tomorrow we can completely change the implementation of the concrete classes such as rectangle on how it draws without even client knowing it or maybe add a feature. All client needs to say is whether it wants to draw a shape or fill color.

You can either make AbstractFactory has a abstract class or an interface(Although interface is a best option).

Now lets see how client consumes the factory.

public class Client{
private FactoryProducer producer;
...

public void drawShapes(string shape){
AbstractFactory shapesFactory = producer.getFactory("SHAPE");
Shape shape= shapesFactory.getShape(shape);
shape.draw();
}

public void fillColors(String color,Shape shape){
AbstractFactory colorsFactory = producer.getFactory("COLOR");
Color c= colorsFactory.getColor(color):
c.fill(shape);
}
...
}

Curious case of dependency

Now if your thinking what if there are dependencies to create Circle and Rectangle shapes?

Either the client class should implement dimension interface that exposes radius, height and width dimensions. Or in some cases when dependencies are individual classes, then factory should take care of creating dependency object, take a look at example below.

public class CarFactory{

public Car getCar(String type){
switch(type){

case "SEDAN":
V4Engine engine = new V4Engine();
AutomaticGear gear = new AutomaticGear();
return new AudiA6(engine,gear);
break;

...
}
}
}

Further Reading

  1. https://stackoverflow.com/questions/2280170/why-do-we-need-abstract-factory-design-pattern
  2. https://medium.com/software-engineering-101/design-patterns-abstract-factory-39a22985bdbf