Factory Method Design Pattern in Swift

In this article I am going to discuss how you can implement the Factory Method Design Pattern in Swift programming language

According to the GoF definition you can define Factory method like below

Definition

Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

This is the UML diagram for Factory Design Pattern. Now we will study the each component in the diagram

Participants

Product
Product is the interface of the ConcreteProduct which Factory creates

Concrete Product
implements the Product interface

Creator

– declares the factory method, which returns an object of type Product. Creator may also define a default implementation of the factory method that returns a default ConcreteProduct object.
– may call the factory method to create a Product object.

Concrete Creator
Overrides the factory method to return an instance of a ConcreteProduct.

Factory Method Design Pattern Example in Swift

Now we will try to implement the Factory Method design pattern in Swift 3

Smart Shirt Inc is a garment factory which produce quality garments. It has several departments for producing Shirts, T-Shirts,Trousers etc. Shirt department produces two types of shirts which are long sleeve shirts and short sleeve shirts

To represent the above information we can draw following UML diagram

Now we will implement the above diagram in Swift code

IShirt (Product) is the protocol which is the equivalent to the interface of other program like Java,C# etc

Next I am going to create two ConcreteClasses named LongSleeveShirt and ShortSleeveShirt. These classes use the proptotype IShirt and implement its make() method

Next I am going to create IShirtFactory proptotype which is equivalent to the Product interface in general UML diagram. This prototype has createShirt() method

Once you create the IShirtFactory proptotype you can create the ConceteProduct class ShirtFactory

Now you have created all classes and prototypes required for Factory Method Design Pattern. It is time to test the code now. So we will do the Client code now

Finally you can have the following output
Short Sleeve Shirt Produced
Long Sleeve Shirt Produced

Leave a Reply

Your email address will not be published. Required fields are marked *