DEV Community

Cover image for Abstract Factory Method Pattern
Eyuel Berga Woldemichael
Eyuel Berga Woldemichael

Posted on • Edited on

Abstract Factory Method Pattern

Abstract Factory Method(kit) provides an interface for creating suits of related objects without specifying their concrete classes

Motivation

Consider an application which supports different standard of appearance and behavior. Each component in a standard should be used together. Hard-coding this standards will pose a problem as it will not be portable. We also should not mix the components that make up the standard.

The Abstract Factory method pattern solves this problem by providing the necessary interface for creating an appropriate class instance. And also enabling clients to work with interfaces, without worrying about the concrete classes.

Applicability

The abstract factory method pattern can be used in cases where:

  • Configuration of the system requires a suite of products.
  • Implementation of products must be hidden and only their interface disclosed
  • Suites of objects must be used together

Structure

Abstract Factory Class diagram

Participants

  • AbstractFactory: Interface for methods that create abstract products
  • ConcreteFactory: Implementation for methods that create abstract products
  • AbstractProduct: Interface for Product object
  • ConcreteProduct: Implementation of the AbstractProduct interface.
  • Client: Use interfaces declared by AbstractFactory and AbstractProduct classes.

Collaborations

  • AbstractFactory transfers the responsibility of product object creation to its concrete sub- classes

Advantages

  • Promotes loose-coupling between client and concrete products
  • Increased flexibility in code as new variants of products can be integrated without changes in client code

Disadvantages

  • Increased complexity in code due to increase in new interfaces and classes

Implementation

Applications generally need one instance of a Factory, so they are typically implemented as Singletons. The AbstractFactory does not have an implementation for product creation and the ConcreteProduct sub-classes commonly define factory methods for this purpose.

Demo

Following up on our cafe example:

There are now several new branches of the cafe and we have managed to change the language of the menu for each branch. But the owners now want each branch to have unique interior design. Each branch will have a different look, the pictures on the wall and the staff uniform should be different.

To solve this problem, we create interfaces for WallPicture and StaffUniform. Then we create concrete classes that implement these interfaces. After that, we create an abstract BranchFactory class that will return WallPicture and StaffUniform objects. Lastly we will create a static class FactoryCreator to generate BranchFactory object based on the information passed.

Top comments (0)