The Abstract Factory Pattern for Beginners | by Márcio Júnior | Jun, 2021 – DzTechno


The Abstract Factory pattern belongs to a category of patterns called Creational because it deals with object creation. Creational patterns abstract the process of object creation. The Abstract Factory focuses on families of objects, while the others focus on one kind of object. From now on, we will call objects products.

Diagram explaining Abstract Factory pattern
Image by the author.

This diagram shows two families of related products: Square and Circle. Let’s start by creating an abstraction of it:

interface ISquare
{
void Draw();
}

The diagram also shows concrete classes implementing interfaces. It could be a different type of square (e.g. Square3D). I will omit this for brevity (and because I don’t like to read articles that have big chunks of code). Just consider these two abstract products and your four concrete implementations.

Now we need a factory to create them, right? No problem:

interface IFactory
{
ISquare CreateSquare();
ICircle CreateCircle();
}

This is what gives the pattern its name: Abstract Factory. But as you may know, we can’t instantiate an interface. Will this factory create a regular square or a 3D one? I don’t know. We need to provide a concrete implementation to each factory responsible for creating the products. Here is the example for 3D shapes:

class Factory3D : IFactory
{
public ISquare CreateSquare()
{
return new Square3D();
}
public ICircle CreateCircle()
{
return new Circle3D();
}
}

Notice that a factory creates products of different families: Square and Circle. But they are related to each other as 3D shapes. It’s possible because they share the same interface, although they are in different families. In the same way, factories also share the same interface. This allows us, as clients, to select one family, and then all products will belong to that family:

IFactory factory = new Factory2D();
ISquare square = factory.CreateSquare();
square.Draw();

We could simply swap to another factory and replace the entire family of products.

Leave a Reply

Your email address will not be published. Required fields are marked *