Abstract Factory

Lucas Ferreira Machado
3 min readMar 29, 2021

A creational pattern

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

REAL PROBLEM

Consider that you created an ordering software to a grocery store that stores data in a MySQL database.

DAO classes

What to do if you need to support other databases, like Oracle and SQL Server?

A large supermarket is interested in its software but requires that the data be stored in the Oracle database.

The oracle database is requested but we know that exists many other databases like SQL Server.

A SOLUTION

In order to make easy to support Oracle and other databases in the future we will use the Abstract Factory pattern.

First we need to separate the family of types involved.

We had the DAO classes for like CustomerDAO, OrderDAO and PaymentDAO to manage the data in the MySQL database. In the other side we had the databases MySQL, Oracle and SQL Server.

LET'S CODE IT !

1 . Create an interface DAO that defines the methods involved like create, read, update and delete.

2 . Then create an abstract factory class DAOFactory that declares a method to create each type of DAO like CustomerDAO, OrderDAO and PaymentDAO.

3 . There is also an abstract factory class for creating DAO for each database type like MySQLDAOFactory, OracleDAOFactory and SQLServerDAOFactory.

4 . And then the concrete subclasses implement DAO for a specific database.

USAGE

Consider the following abstract factory class.

Create a single method to create the DAOFactory instance related of the database type configured in the settings of GroceryStore application:

Let's put it into DatabaseController class:

Finally, create the DatabaseController passing the database settings.

SOURCE CODE

You can find the complete JAVA source code of this sample at Github https://github.com/lucasferreiramachado/designpatterns

BENEFITS

It makes possible to add other kinds of the same family without changing the current software architecture.

Recommended for systems:

  • have families of related or dependent types
  • may need to support new types (categories, versions, technologies, etc)

For example this pattern can be applied when a system has to support different platforms like Windows, Linux and Mac OSX and probably this range can increase in the future.

Important note

Change any interface impact on all concrete subclasses. Adding new methods to the DAO interface takes a lot of work, for example.

WHAT ELSE MAY THIS APPLY ?

Here are some possible use cases.

What’s next

Start learning about the creational pattern Builder: https://lucasferreiramachado.medium.com/builder-pattern-8dfd77720812

--

--