2015-10-02

In Abstract Factory Design Pattern provides an interface or abstract class for creating a family of related or dependent objects, without explicitly specifying their concrete classes. It comes under creational pattern as it abstract the complex logic of creating various related object from client. It allows a client to use an interface to create a set of related objects without knowing about the concrete classes that are actually produced.

An Abstract Factory is a super factory which creates other factories. In other words, it is a factory of factory classes or It is a wrapper over factory Pattern.

Advantages of Abstract Factory Pattern

Abstract Factory pattern relies on object composition, as object creation is implemented in methods of factory interface.

It is a powerful technique that supports this major design principle "Program to an interface not an implementation".

It promotes loose coupling between client and concrete sub-classes.

It supports consistency among objects. It is the concrete factory’s job to make sure that the right objects are used together.

When we should use Abstract Factory Pattern

When we want to abstract the logic of object creation and want system to be independent of ways its objects are created.

When a system needs to create a similar or related set of objects.

When you want to expose an abstract library for creating families of similar objects through interfaces and by hiding implementation details.

Implementation of Abstract Factory Design Pattern

We are going to create a 'Bird' and 'Animal' interfaces and concrete classes of various birds and animals implementing these interfaces.

Bird.java

Eagle.java

Sparrow.java

Animal.java

Lion .java

Horse.java

Next, we create an abstract factory class AbstractFactory which is extended by 'BirdFactory' and 'AnimalFactory' factory classes.

AbstractFactory.java

AnimalFactory.java

BirdFactory.java

Then we will create a 'FactoryCreator' class to get appropriate AbstractFactory instances as per the passed input parameter. Finally we will create 'AbstractFactoryPatternSample' which uses and instance of FactoryProducer to get concrete implementation of AbstractFactory and creates various animal and bird objects.

Output

Important Points about Abstract Factory Pattern

The intent of Abstract factory design pattern is to create families of related objects without having to depend on their concrete sub-classes.

The client doesn't know what factory it's going to use. First, it gets a Factory and then it calls factory method to get concrete classes.

It is a factory of factories.

Show more