The Factory Pattern using Swift
Create objects the right way!
--
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 interface we are provided with an abstraction rather than a concrete type, so code is protected from unwanted implementation details.
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.
Since we are using Swift this overriding is NOT something that we would usually do. Overriding a function? I’d rather not, thank you.