📖

Swift factory method design pattern

The factory method design pattern is a dedicated non-static method for hiding the creation logic of an object. Let's make it in Swift!

Swift iOS design patterns

Factory method is just a non-static method

Let's face it, this pattern is just a method usually backed by simple protocols & classes. Start with a really simple example: imagine a class that can create a base URL for your service endpoint. Let's call it service factory. 😅

class ServiceFactory {
    func createProductionUrl() -> URL {
        return URL(string: "https://localhost/")!
    }
}
let factory = ServiceFactory()
factory.createProductionUrl()

You might think, that hey, this is not even close to a factory method pattern, but wait for it... let's make things a little bit complicated by creating a protocol for the service class and a protocol for returning the URL as well. Now we can implement our base production URL protocol as a separate class and return that specific instance from a production service factory class. Just check the code you'll get it:

protocol ServiceFactory {
    func create() -> Service
}

protocol Service {
    var url: URL { get }
}

class ProductionService: Service {
    var url: URL { return URL(string: "https://localhost/")! }
}

class ProductionServiceFactory: ServiceFactory {
    func create() -> Service {
        return ProductionService()
    }
}

let factory = ProductionServiceFactory()
let request = factory.create()

Why did we separated all the logic into two classes and protocols? Please believe me decoupling is a good thing. From now on you could easily write a mocked service with a dummy URL to play around with. Obviously that'd need a matching factory class.

Those mock instances would also implement the service protocols so you could add new types in a relatively painless way without changing the original codebase. The factory method solves one specific problem of a simple factory pattern. If the list - inside the switch-case - becomes too long, maintaining new objects will be hell with just one factory. Factory method solves this by introducing multiple factory objects.

Share this article
Thank you. 🙏

Get the Practical Server Side Swift book

Swift on the server is an amazing new opportunity to build fast, safe and scalable backend apps. Write your very first web-based application by using your favorite programming language. Learn how to build a modular blog engine using the latest version of the Vapor 4 framework. This book will help you to design and create modern APIs that'll allow you to share code between the server side and iOS. Start becoming a full-stack Swift developer.

Available on Gumroad
Picture of Tibor Bödecs

Tibor Bödecs

CEO @ Binary Birds

Server side Swift enthusiast, book author, content creator.