In this article I'll teach you about the static factory design pattern and show some use cases using the Swift programming language.
Real world static factory pattern examples
The first good thing about the static facotry pattern is that every static facotry method can have a name. Apple uses this pattern in their
UIColor class implementation to create named colors like
.yellow, etc. Please note that the implementation in Swift is not really a method, but a static property, which returns the actual instance.
If it's so hard to memorize how many seconds is a day or a week why don't we create a named initializer for it. See?
TimeInterval.week is much better than
The next good thing about the static factory pattern is that it can support caching for the sake of better memory usage. This way you can limit the number of objects created if you are initializing it through the static constructor (aka. static factory method). 🏭
Local initialization scope
Another good thing about static factory methods that you can limit the initialization of a class to a private scope level. In other words object creation will only be available through the static factory method. You just have to make the init method private.
Note that you can restrict subclassing with the final & static keyword. If you want to allow subclassing you should remove
final and use the
class keyword instead of the
static for the properties, this way subclasses can override factory methods. 🤔
Statically return anything
Static factory can also return subtypes of a given object, but why don't we take this even one step further? You can also return any kind of type from a static method, I know this seems like a cheat, because I'm not creating an instance of
UIColor here, but I believe that it's worth to mention this method here, becuase it's closely related to static factories. This technique can be really useful sometimes. 😛