Java: Abstract Factory Pattern

Akash Panchal
NestedIf
Published in
2 min readDec 15, 2018

A Creational Design Pattern

Photo by Dai KE on Unsplash

Before you start, heads up to here for the simple introduction to the design patterns and the index to all the design patterns deep tutorials.

Defined

The Abstract factory pattern provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes.

When to use?

When there are interrelated dependencies with not-that-simple creation logic involved.

Example

Translating the Wheel example, First of all, we have our Wheel interface and some implementation for it.

Then we have some fitting experts for each wheel type.

Now we have the abstract factory that would let us make a family of related objects. And We will require to create a Factory Producer who creates an appropriate factory for us.

Below is the code FactoryProducer

Let’s try it out generating a Factory

As you can see the car wheel factory has encapsulated the car wheel and the car expert also, bike wheel factory has encapsulated bike wheel and bike expert. And thus it had helped us make sure that for each of the created wheel, we do not get a wrong fitting expert.

Find the code used in this article on github.

If you like this post, please click the clap 👏button below a few times to show your support!

--

--