It is very similar to Factory Pattern except that it’s more like factory of factories.

We know that Factory pattern produces different concrete classes based on the input supplied to factory class by implementing if-else conditions within the factory class.

Definition of Abstract Factory

Provides an interface for creating families of related or dependent objects without specifying their concrete classes.

In other words,Abstract Factory pattern allows us to define an interface for creating all distinct products, but leaves the actual product creation to concrete factory classes.

Each factory class corresponds to a certain product variety.

In other words.Abstract factory pattern will have one interface called “ abstract factory ” which will have several subclasses and each of these subclass is called as“ factory ” and each subclass factory can then be used like factory pattern to produce the set of related objects.

GOFs representation of Abstract factory pattern

Let us consider below requirement

We need to read data from different machines like windows and Mac.

Also we need to read different formats of data like pdf,excel etc.

Now we need to use Abstract factory pattern to solve this requirement.

So we will create one abstract factory and 2 sub class factories to represent Mac and windows

Each of these factories Mac and windows produces 2 different set of objects

one to represent PDF data format and other one to represent Excel data format

Let us do this step by step

Step1

Create one abstract class which will be the parent class for all subclasses which factory produces.

In the above class, we are passing required file format and appropriate sub-factory class and we get the appropriate object gets created from factory and then we have called readData() method of that object

We can see that, in the first case,we have passed format as pdf and sub factory as ReadWindowsDataFactory and in the second case we have passed format as Excel and sub-factory as ReadMacDataFactory

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com