Factory Method in Swift

Jeremi Kaczmarczyk
Swiftier, faster, better
2 min readAug 27, 2016

Another post got delayed, this time due to running workshops on ProMobiConf in Warsaw. For the first time I had to prepare 5 hours long session on advanced Swift topics. It was great experience, and I hope after some polishing I will make materials and code from it public on my github. But on to the topic of today’s article…

Abstract … Factory … Method? 😩

So here comes another “Factory” design pattern. And it is not even the last as we have few more of them called the Simple Factory and the Static Factory, but I won’t cover them in this series as they are not part of GoF book. When preparing for this article I found 2 insights about those patterns:

  1. Abstract Factory is often implemented using Factory Method(s) as I unconsciously did in previous post.
  2. Abstract Factory is for creating families of objects and Factory Method for individual objects.

Personally I try to imagine that Abstract Factory influences whole application or major part of it, while Factory Method works very localy.

DIY: Factory Method ⚙

To make yourself one we will need:

Product- interface of objects genereated by the Factory Method here in our case it is the Game protocol.

Concrete Product- implementation of Product protocol.

Creator- usually abstract interface or initial implementation with method createProduct(), can generate base Product.

Concrete Creator- implements / subclasses Creator, and generates Concrete Product with createProduct().

Well there are no objections to play a little with those actors. In implementation below, Concrete Products are also Concrete Creators, ad it its legitimate Factory Method implementation.

To sum it up the Factory Method is function responsible to create an object (or value in Swift 😉) it might be part of the object itself, or the object that needs produced object.

The problem I got when describing design patterns is that simple implementations often do not allow to fully appreciate the pattern, but complex ones are too big for elegant blog post.

So who plays 🏀? GSW are doing great, but Rose in NYK sounds interesting. See you next week where we will continue our journey with the Prototype pattern.

--

--