Factory Method in Swift
Factory Method is a creational design pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created.
When We Use Factory Method?
Imagine you have a logistic management application. The first version of your application can we handle transportation by trucks, so the bulk of your code lives inside the Truck class.
One year later your app become pretty popular each day you have many request from sea transportation company to incorporate sea logistics into the app, it's great news right? But how about code? What do you do?
You should refactor Truck class to adding Ships into app you should modify all the class and it's takes a long time.
In this time I have a great news for you if you use factory method you don't need modify all the classes that you have been write before.
Factoring method suggest you to use protocol for this problem. But how?
For example, both Truck and Ship classes should implement Transport protocol, which declares a method called deliver. Each class implements this method differently: trucks deliver cargo by land, ships deliver cargo by sea.
Use the Factory Method when you don’t know beforehand the exact types and dependencies of the objects your code should work with.
Pros and Cons
➕ Single Responsibility Principle. You can move the product creation code into one place in the program, making the code easier to support.
➕ Open/Closed Principle. You can introduce new types of products into the program without breaking existing client code.
➕ You avoid tight coupling between the creator and the concrete products.
➖ The code may become more complicated since you need to introduce a lot of new subclasses to implement the pattern. The best case scenario is when you’re introducing the pattern into an existing hierarchy of creator classes
Relations with Other Patterns
- Many Developers start by Factory Method (less complicated and more customizable via subclasses) and evolve toward Abstract Factory, Prototype, or Builder (more flexible, but more complicated).
- Abstract Factory classes are often based on a set of Factory Methods, but you can also use Prototype to compose the methods on these classes.
Source: Dive Into Design Patterns Book