Factory design Pattern in iOS
Design patterns give us a predefined tried and tested solution to some of the commonly occurring problems in programming. Design patterns leverage tremendous flexibility while programming. These have been widely popular in the programming community and provide a great way of having a language of communication between developers.
For example when someone says factory, I know its an abstracted form of creating different types of objects, when some one says adapter I know this is something which is connecting two interfaces.
Design patterns can be broadly divided into 3 categories
- Creational Patterns
- Structural Patterns
- Behavioural Patterns
Creational Patterns
Creational patterns deal with object creation mechanisms. Throughout our app development we create many objects and we may some times run into situations where the object creation logic gets complex and does not provide reusability when a new type of object needs to be added. Creational patterns give a more general and flexible approach for the same.
Factory Pattern
In the factory pattern we create an object instance which acts as a factory taking on the responsibility of creating objects. The factory returns one or several types of objects based on the data provided to it
Example — Suppose your app has smaller products within it. Each with its own look and feel and other internal functionalities. But your client which shows these does not need to know the details of these different products. The client is only interested in adding and removing the products. We can use a factory pattern for cases like this
Lets first crate a product protocol with defines the functionalities of the product facing the client

- The Product protocol defines two functions. One to show product and the other to remove product
- Next lets create ProductA and ProductB which will implement the Product protocol

3. Now lets create a factory instance which has a createProduct function. createProduct takes an argument product type and returns the product instance.
4. Now whats the advantage of this setup. Suppose you have a view controller whose function is only to show and remove products, all he has to do is have an instance of the ProductFactory class and give him a type. It will return a Product type and now the controller can easily add or remove many products easily . The controller need not bother about the product creation logic.

Advantages
- The client does not need to know what every subclass of objects it needs to create
- The factory encapsulates object creation which is really helpful when the object creation logic is very complex
Factory pattern aids in reusability when a new type needs to be added. For example if I add a ProductC in the above example all I need to change is the ProductFactory and add the new type. The rest of apps functionality will work automatically without much hassle.
Factory design pattern for the rescue !
