Home Articles

Abstract Factory Pattern

Let us discuss how abstract factory design pattern in this article:

Factory Design Pattern


This pattern allows a consumer to create a group of related objects whose relationship is not expressed through a common protocol like ProductA1 and ProductA2 may conform to a different protocol. And it hides the implementation details of which classes are used to create the objects.

What are the benefits?

The consumer doesn’t know which classes are used to create the objects or why they were selected, which makes it possible to change the classes that are used without needing to change the components that consume them.

When should you use this pattern?

This pattern is useful when multiple compatible objects are used by a consumer without needing them to know which objects can work together like goods of same model.

When should you avoid this pattern?

When you need single object

Pattern correct implementation check:

This pattern is implemented correctly when a consumer receives a set of objects without knowing which classes were used to instantiate them. The consumer should be able to access the object’s functionality only through the protocols.

When this pattern can go wrong?

When we leak details of the classes to the consumer, either creating a dependency on the decision-making process that selects classes or creating a dependency on specific classes.

Any related patterns?

It can often be combined with singleton, prototype and composition.


Design Pattern Structure

Snippet 1

Consumer would just call makeFactory(for: .ikea) and it would return IKEAFactory object.

Snippet 2

Snippet 3

Consumer is not aware of how FurnitureFactory was built for any requested brand. The abstract factory should contain the decision logic only for selecting a concrete factory and not for implementation classes. Similarly, the concrete factories should contain the logic for selecting implementation classes and should not provide any of the functionality defined by the product protocols.

Patterns that could be used with this Pattern:

Here I have used a singleton pattern to get a furniture factory for a requested brand. In Object Pool pattern you need to store objects in the queue. Different combinations of objects may lead to deadlock when two components have acquired a free object required by the other. Object pooling works best when all of the components require the same type of object.

This is a free third party commenting service we are using for you, which needs you to sign in to post a comment, but the good bit is you can stay anonymous while commenting.