The Factory Pattern using Swift

Create objects the right way!

Steven Curtis
3 min readFeb 25, 2021
Photo by Manja Vitolic on Unsplash

Difficulty: Beginner | Easy | Normal | Challenging

The factory pattern provides an interface for creating objects in a superclass. This article provides some details around this design pattern, and also has some examples of it! We should get building!

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.

The idea of this article is to cover both.

Why use a factory?

Complexity

Instantiations may be complex, and encapsulating instantiation can simplify creating concrete instances by defining a single place. This means that we can follow the Dependency Inversion Principle, and even open the door to dependency injection.

Decouple the use of an object from creating it

We can abstract our code, so where modifications are made to a class the client of that class can continue to use it without further modificaiton. By implementing to an…

--

--

Responses (1)