Abstract Factory Pattern in Java

Well, if had read my previous article on Factory Design Pattern in Java, this would be much simpler. I felt that abstract factory is a factory of factories.

When Abstract Factory ?

Ionic app ported to IOS and Android.

Similar things can be seen in the case of Ionic. Ionic had UI components like Button, Dialogue etc. Based on the OS (Android, iOS, Windows), the correct component will be instantiated.

What is the difference between Factory & Abstract Factory?

With the Abstract Factory pattern, you provide a way for anyone to provide their own factory. This allows your warehouse to be either an IFruitFactory or an IJuiceFactory, without requiring your warehouse to know anything about fruits or juices.

Project Structure:

Android Example :

UI Components for Different versions of Android.

Suppose I am creating a Material UI Library for Android. For this current discussion, we limit ourselves to Material Dialogue Box.

For older versions of android (Lollipop), Dialogue Box’s might not support GIF’s and Animations. While for latest version (say Nougat) it supports GIF’s and Animations but may require an explicit permission to be provided(For may be File Upload).

We create two Factories.

  • LollipopFactory
  • NougatFactory

LollipopFactory is factory to instantiate different kinds of dialogues for Lollipop : Info Dialogue, Error Dialogue, File Dialogue etc.

Similar NougatFactory is factory to instantiate the above mentioned, for Nougat.

Finally we have WidgetFactory which takes input as ANDROID.VERSION and instantiates & returns the respective Factory at Run-time.

Implementation in Java

IFactory.java

Concretions of the above Factory.

LollipopFactory.java

NougatFactory.java

2. Create the fundamental products of every factory. In our case Dialogue Box, Input Box etc.

IDialogueBox.java

3. Create products of sub-factory. ie LollipopFactory and NougatFactory.

Lollipop: 🍭

LollipopErrorDialogueBox.java

LollipopInfoDialogueBox.java

Nougat 🍫

NougatErrorDialogueBox.java

NougatInfoDialogueBox.java

4. Create Parent Factory which delegates the method calls to respective sub-factories based on ANDROID.VERSION.

WidgetFactory.java

5. Finally a Driver to test this out.

Similar Examples:

Found it Interesting?
Please show your support by 👏. To read the complete series, click below.

Reference:

Disclaimer:
I myself, has just started learning, design patterns. If you find any issues please feel free to post them in the comments section below. Thank you for reading so far 😄

Writes on Big Data, AWS & Backend technologies.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store