The Factory Pattern using Swift

Create objects the right way!

Photo by Manja Vitolic on Unsplash

A factory

In programming, a factory is an object for creating other objects. In Swift that object will typically be a class, and will produce a concrete instance of an object. In the original book it is declared that there is no strict factory pattern, but rather a factory method pattern and an abstract factory pattern.

Why use a factory?

Complexity

The difference between a factory method and an abstract factory

The factory method is (well, obviously) a method, and an abstract factory is an object. Factory methods can be overridden in a subclass. An abstract factory is an object that can have multiple factory methods.

The Factory Method Pattern

A factory protocol will return new objects. In Swift we usually code to a protocol, an extension could provide a defailt implementation but there will usually be a concrete instance of this factory.

The Abstract Pattern

This particular guide is going to give you a definition for the abstract factory pattern.That is, the abstract:

The Factory example

We can set up a factory method for the property initialization, this lives inside an abstract factory.

A Factory making use of Enum

It can make sense to create a complicated object using Swift’s rather nice Enum. Now this isn't something I've used in production (for a URL) since I use my own URLBuilder for this functionality, but this gives a good example of using a factory in real code!

Conclusion

This is used in my article Dependency Injection using Storyboards, and I would recommend that you think seriously about using the factory pattern — in Swift projects it is rather well-used as well as being useful for conversations about projects.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store