Design patterns #3: Factories

Hi and welcome to this episode of this article series about design patterns. In today’s episode we’ll try to cover a lot, from the concept of Factory to some code implementations of the Absctract Factory and the Factory Method design patterns. I’ll do my best so that by the end of this article you have a deep understanding on this topics in deep.

So let's get started!

Factories

Let's begin by defining what does mean the word factory in the programming world:

A factory is an object for creating other objects.

As simple as that, those 9 words define the concept of factory. But, I know, this is so minimalist, you may except something more elaborated. So here you go:

More formally you can tell that a factory is factory is function, method or subroutine that returns objects of a varying prototype or class.
this definition looks more professional… but i'm a simplistic guy so I prefer the first one.

In a class-based programming language, you can see a factory as an abstraction of a constructor of a class, while in a prototype-based programming language you can see it as an abstraction of a prototype object. Factories may be invoked in various ways, most often a method call (factory method), sometimes by being called as a function if the factory is a function object (factory function).

Factory isn't a pattern but a concept

There is some confusion around whether the concept of a factory is itself a design pattern. Formally there is not a design pattern named “factory pattern”, but instead two patterns (factory method pattern and abstract factory pattern) that use factories. In many languages factories are invoked by calling a method, and because of that the general concept of a factory is often confused with the specific factory method pattern design pattern.

Nevertheless, there are some design patterns that internally make use of factories such as Singleton, Builder, Abstract Factory, Factory method…

Examples

Below you can see some implementation of factories in various languages:

Javascript factory function

C# factory method

Java factory method

The Factory Method pattern

Define an interface for creating an object, but let sub-classes decide which class to instantiate. The Factory method lets a class defer instantiation it uses to sub-classes. — (Gang Of Four)

In class based programming languages, Factory Method is a design pattern that pertains to the creational family. This pattern uses methods to deal with the process of creating objects without having to specify the exact class for the object that will be created. This is achieved by a factory methods — either specified in an interface and implemented by child classes, or implemented in a based class and optionally overridden by derived clases — to create the appropriate object instead of calling a specific constructor.

As you can see the Factory Method pattern strongly relies on the concepts of interfaces and inheritance, as the object creation is delegated to subclasses implementing the factory method.

The problem

Object creation may lead to a significant duplication of code and not provide a sufficient level of abstraction. More often than not, creating an object requires complex processes not appropriate to include within a composing object because is not part of the composing object’s concerns. Also object creation may require information not accessible to the composing object creating the object.

The solution

The Factory Method pattern handles these problems by defining a separate method for creating the objects, which sub-classes can then override to specify the derived type of product that will be created.

Benefits

Factory methods have descriptive names. In fact, several factory methods for creating the same object have different names describing the process that creates that object. This is an advantage over the constructor, as in many object-oriented languages, constructors must have the same name as the clase they are in, which can lead to ambiguity if there is more than one way to create an object.

Also factory methods encapsulate the creation of objects. This is particularly useful because it hides all the complexity of creating an object away from the client code.

Sadly this pattern have its pitfalls too, we'll talk about them next.

Pitfalls

Refactoring an existing class to use factories breaks existing clients of that class because now they have to replace the call to a constructor by the call to the desire factory method.

Also since the pattern relies on using a private constructor, the class cannot be extended. Any subclass must invoke the inherited constructor, but this cannot be done if that constructor is private. If the class were to be extended (e.g., by making the constructor protected — this is risky but feasible), the subclass must provide its own re-implementation of all factory methods with exactly the same signatures, if not the children clases will yield an instance of the superclass rather than the expected instance of the subclass.

Implementations

Wikipedia provides with some implementations of this pattern in various programming languages, here I show one of them…

The Abstract Factory pattern

Provide an interface for creating families of related or dependent objects without specifying their concrete classes.

Once you've understood the concept of factory and the Factory Method pattern I hope you find the Abstract Factory pattern pretty easy as it is mostly the same thing, just addressed to solve abstraction issues.

Basically, the Abstract pattern provides a way to encapsulate a group of individual factories that have have a common theme without specifying their concrete classes. Normally, the client software creates a concrete implementation of the abstract factory and then uses the generic interface of the factory to create the concrete objects that are part of the theme. The client doesn’t care which concrete implementation it gets from each of these internal factories, since it uses only the generic interfaces of their products.

The problem

Often, in software development, programmers find themself struggling with the dilema of having to work with several implementations of the same interface based on different criteria like the OS appearance, the Data Source, etc. When given this escenario is a good practice to abstract the instantiation of the different implementations so the client code can use transparently and seamlessly whichever of them.

Benefits

This pattern separates the details of implementation of a set of objects from their general usage and relies on object composition, as object creation is implemented in methods exposed in the factory interface. When using this pattern, you are able to interchange the concrete implementations without changing the client code.

Pitfalls

The employment of this pattern, as with similar design patterns, may result in unnecessary complexity and extra work in the initial writing of code. Additionally, higher levels of separation and abstraction can result in systems which are more difficult to debug and maintain.

Implementations

Wikipedia provides with some implementations of this pattern in various programming languages, here I show one of them…

This is the interface every factory must implement.

This is the interface the product must implement.

This are some implementations of the product.

These are some implementation of the IGUIFactory interface.

Now we can see how the client code doesn't care what specific implementation of the the IGUIFactory is returned. The client code will never change but it will do different things based on what implementation of the IButton interface it gets from the abstract factory.

Conclusion

In this third delivery we've had a deep introduction to the concept of factory as well as the Factory Method and the Abstract Factory design patterns. Now we know how to abstract and encapsulate the object creation process on our systems so we can get rid of all the complexity and code duplication related to it. Hope you’ve found this article helpful and you come back to the next one about the Prototype pattern.

Follow me to stay up-to-date on this and other article series.
Also remember follow me on twitter,
twitter.com/@modestofiguereo.

If you liked this article I invite you to recommend it and if you have any doubts or contribution comment it bellow.

Happy coding ❤