Abstract Factory Pattern

 
What is Abstract Factory Pattern ?

Abstract Factory Pattern is a creational design pattern. This pattern creates a super factory which in turn creates other factories. Abstract Factory pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes. This pattern provides with a way to encapsulate concrete factories that share some similarity with each other, meaning they implement same interface or abstract class.

When to use Abstract Factory Pattern ?

When you want to defer the decision about which factory to use is made at runtime.
Let’s implement this design pattern.

To implement this design pattern let’s take an example of Car factory which manufactures Cars and Bike Factory which manufactures Bikes. Car Factory creates different types of Cars whereas Bike factory creates different types of Bikes. Let’s create all the classes required to implement this design pattern.

First Create all the classes required for Car Factory.

Car.java:

Create a Car interface.

Lets create the concrete implementing classes of Car interface .

HondaCar.java:

HondaCar.java implements the Car interface.

MarutiCar.java:

MarutiCar.java implements the Car interface.

TataCar.java:

TataCar.java implements the Car interface.

Let’s create all the classes required for Bike Factory.

Bike.java:

Create a Bike interface.

Lets create the concrete implementing classes of Bike interface .

HondaShine.java:

HondaShine.java implements the Bike interface.

BajajPulsar.java:

BajajPulsar.java implements the Bike interface.

TVSApache.java:

TVSApache.java implements the Bike interface.

Let’s create the AbstractFactory interface to get the factories for Car and Bike objects.

AbstractFactory.java:

Now create the CarFactory.java class which implements the AbstractFactory interface and will return the Car objects.

CarFactory.java:

Now create the BikeFactory.java class which implements the AbstractFactory interface and will return the Bike objects.

BikeFactory.java:

Let’s create the AbstractFactoryDemo class to check the results.

AbstractFactoryDemo.java:

Output:

Check the output. Car and Bike factories are created.

Related posts

Leave a Comment