What Is an Abstract Factory Pattern?

The Abstract Factory pattern is a creative way to expand on the basic Factory pattern. Since the Factory pattern is a class that creates other classes in a uniform way, the Abstract Factory pattern gives us a way to allow factories with similar methods and access points to be interchangeable. That is, using an abstract factory we can define implementation class types as factories with the abstract factory as the base, and thereby tie in all the different factory implementations to a base class.

So now that we have a basic explanation of what an abstract factory is, let’s talk about how this is useful in our code. Let’s start by discussing what factories actually do in code and why they are valuable.

A factory class is a way to compartmentalize code that creates other classes and types. It can initialize, pull in data, configure, set state, and perform nearly any other creational operation needed. An abstract factory then is generally used when you may have multiple factories that do different things for a class type, and you wish to provide uniformity between these factories. So let’s say you have two different factories. Each one has slightly different creational logic and renders a particular class type. If each of these factories rendered the same class type, but differed in how they create the class type as an instance, we could tie both those factories together using an abstract factory class as a base. Now if we wanted to use the two factory classes interchangeably for different situations but still return the same class type, we could do so without having to rewrite the code that calls the factory to explicitly call a particular factory class type.

The Abstract Factory pattern has two main components: the Abstract Factory and the Abstract Product. The abstract factory class holds the definition for creating the concrete implementations of the factory, including the abstract method references. The abstract product class is the definition for the concrete implementations of the class that the factory renders.

Pin It on Pinterest

Shares

Get the best in web dev

Join dunebook.com and recieve best in web dev , once a week FREE

An email has been Sent to your Inbox ! Please Confirm your Subscription :)