Factory Method Pattern in Swift

Tram Ho


The ‘Factory Method’ pattern is a creational design pattern, abstracting the creation process. The creative model controls who creates an object and what / how / when it is created.

The ‘Factory Method’ pattern defines the interface to create objects and delegates the creation of objects to subclasses.

When should we use this pattern?

Provide interface to create objects

This pattern should be used when we have many different objects that we use in different ways. Their initializations can be complex and require calculation to create them. The ‘Factory Method’ pattern encapsulates their initials to simplify their creation on location.

Defining a unique place to initialize this pattern should be used when a class cannot predict the type of object it needs to create. If we have an object that does what we need, we have to reuse and initialize it somewhere in the code. Moving these instances, from the client layer to an interface, makes the class dependent on abstraction and does not make it dependent on low-level components (Dependency Reversal Principle). This interface, called the factory method, has the logic to determine the type of object we need to initialize. Furthermore, delegating the logic to a subclass will avoid code duplication and provide a single place to maintain.

To isolate the implementation of an object from its use

This pattern should be used when the creation and initialization logic is performed by the client. A client is closely associated with an object if its type is used in its class. By moving logic and initializing objects in a subclass, we protect the code from API changes. If some modifications are added to a specific class and its API, the client code will not be affected by changes that it does not care about. By implementing an interface, the factory method returns an abstraction rather than a specific type so that we protect the code from implementation details.

How should we use this pattern?

Let’s start with a common approach for this model. In this example, we are working on a mobile application and we want to create a factory method that is responsible for creating UI components.


Factory Method

Run code in a Playground
Share the news now

Source : Viblo