Easy patterns: Abstract factory

Ruslan Malogulko
ITNEXT
Published in
2 min readSep 10, 2018

--

This article is created in continuation of easy patterns series description and presents Abstract factory pattern which solves the problem of instantiating look-and-feel specific classes throughout the application.

Creational patterns:

Simple Factory

Factory method

Builder

Singleton

Abstract factory (this article)

Prototype

Structural patterns:

Adapter

Decorator

Bridge

Composite

Facade

Flyweight

Proxy

Behavioral patterns:

Visitor

Mediator

Observer

Memento

Iterator

Chain Of Responsibility

Strategy

State

The main essence

This pattern is also known as a Kit.

The Abstract factory pattern describes a method of individual fabrics composition, that are grouped together by some common criteria.

This pattern includes four main roles:

  • AbstractFactory — declares an interface for operations that create product object.
  • ConcreteFactory — implements the operations to create concrete product objects
  • Product — defines a product object to be created by the corresponding concrete factory
  • Client — uses only interfaces declared by AbstractFactory and Product classes.

The idea is really simple. The AbstractFactory defers creation of a product objects to its ConcreteFactory subclass. To create separate product object client have to use separate ConcreteFactories.

Example of use

The abstract factory classes are often implemented with Factory Method pattern. ConcreteFactory is often a Singleton (that is reasonable from the perspective that ConcreteFactory should create a concrete family of classes).

In example we are creating several products: CodeSnippets and CodeParsers. Each code snippet should correspond to specific code parser. That’s why it makes sense to create CodeProcessorFactories that create code snippet and code parser in tandem.

Profit

This pattern isolates concrete classes. It helps you to control the classes of object that application creates. The AbstractFactory interface defines the way a Client should manipulate instances.

This makes it easy to change the concrete factory an application uses. It can use different product configurations simply by changing the concrete factory.

It promotes consistency among products. When the products across in a family are designed to work together, it’s important that an application uses objects from only one family at a time.

Weak places

Extending abstract factories to produce new kinds of Products isn’t easy. AbstractFactory interface fixes the set of products that can be created. Supporting new kinds of products requires extending the AbstractFactory interface, which involves changing of all its subclasses as well.

Conclusion

If you found this article helpful, please hit the 👏 button and feel free to comment below!

--

--