Abstract Factory Pattern: Design Patterns

Abstract Factory Pattern: Design Patterns

Factory of factories
Factory of factories

This Creational Design Pattern also known as factory of factories provides one of the best ways to create an object in large projects.

In Abstract Factory pattern an interface is responsible for creating a factory of related objects without explicitly specifying their classes. Each generated factory can give the objects as per the Factory pattern.

Before proceeding with this blog, it would be great if we have a fair knowledge of the Factory Pattern.

The Abstract factory pattern clubs together related factories. And this clubbing acts as a factory itself. Thus we can call it a super factory or factory of factories.

Implementation

We can have a simple example with 2 factories.

Let us take a look at a self explaining hierarchy:

FactoryProducer

  1. ShapeFactory
    • Circle
    • Rectangle
    • Square
  2. ColorFactory
    • Red
    • Green
    • Blue

All project files and code available in the Github project.

How would the implementation look like in Java:

We have a Shape interface

 

We have a couple of classes that is of type Shape



 

We have a Color interface

 

We will now have couple of classes that are of type color



 

Now first step to building an Abstract Factory pattern, we shall have an abstract class that holds the methods to return the factories this Abstract Factory need to handle.

 

Now our basic implementation of Factory Pattern comes handy with the creation of factories of Shape and Color


 

Now comes our most important the Factory Producer that shall give us the required factory from the Abstract Factory

 

Our client code would certainly look something like this

 

The output would be:

Drawing a Circle
Drawing a Rectangle
Drawing a Square
Painting color Red
Painting color Green
Painting color Blue

 

Difference between Factory and Abstract Factory

  • The main difference between a “factory method” and an “abstract factory” is that the factory method is a single method, and an abstract factory is an object.
  • The factory method is just a method, it can be overridden in a subclass, whereas the abstract factory is an object that has multiple factory methods on it.

 

Advantages of Abstract Factory pattern

  • This pattern provides approach to code for interface rather than implementation.
  • It is “factory of factories” and can be easily extended to accommodate more products.
  • Abstract Factory pattern is robust and avoid conditional logic of Factory pattern.
Please follow and like: