Java Creational Design Patterns – Abstract Factory Pattern

The Abstract Factory Pattern is one of the creational design patterns. We can say Abstract Factory patterns acts as a super-factory which produces other factories. The role of the Abstract Factory is to provide an interface for creating families of related or dependent objects without specifying their concrete classes.

If we are using an abstract factory pattern, then the client program will never create platform objects directly, they ask the factory to perform this task for them. So the factory object has the total responsibility for proving this service for the entire platform family. You can use this pattern if-

  • You need your application to be independent of how its objects are created.
  • To decouple classes and way its objects are created.
  • If your business logic involves families of related or dependent objects.

<Here are ALL Java Design Patterns, explained in detail with examples>

Abstract Factory Pattern by Example

For our understanding of this pattern, we will take a simple example of different types of Bank Accounts. When you are dealing with Bank, for every type of your need there is an account created to track the books.  We will try to apply this pattern on account types like Savings, Current, HomeLoan etc.

To start we will define our core interface, which has a single method to show us the interest rate of that account type.

Now, we will define a few concrete classes, that will implement the above interface.

SavingsAccount

Current Account

Home Loan Account

Education Loan Account

After this, we will define our Abstract Factory abstract class. This class will be extended by different Family Factories such as Account Factory or Loan Factory.

also below are different factories-

LoanFactory

AccountFactory

Last but not least we will add a Factory Provider, which is kind of a wrapper or super factory.

Running the Example

Output:

Conclusion

In this article, we understood the Abstract Factory Pattern with the help of a simple example. While the pattern is great when creating predefined objects and providing abstraction, a new addition of object family might be difficult. To support the new type of objects will require changing the AbstractFactory class and all of its subclasses.

The source code is available in our Github repository.

Download Code

<Here are ALL Java Design Patterns, explained in detail with examples>

Add a Comment

Your email address will not be published. Required fields are marked *