Press "Enter" to skip to content

Factory Design Pattern

The factory pattern belongs in the category of the Creational Design pattern. If you take the word “factory” literally. How does a real factory work? You bring in some raw material and do some processing on it and get an output on the outside. For example:

Raw plastic –> Factory –> Some plastic moulds

As the category suggests itself. In the factory pattern, an interface/class creates an object but lets the subclass infer which object to instantiate. All the subclasses implement a common interface that can have one or more functions. You must be wondering why is there an example of a real factory above?

Well, continue reading.

Class Diagram

Consider the following UML representing the structure of a Class system in airlines.

UML Factory Design Pattern
UML Factory Design Pattern

Implementation

Have a look at the following chunks of code:

SwiftKotlin

Usage

Create an object of TravelClassFactory. Call getTravelClassFrom from the object. Pass in .business/TravelType.BUSINESS as an argument. TravelClassFactory returns a particular TravelClass based on the type.

SwiftKotlin

Pros

It helps in containing all the object creation logic in a single class. It provides you an object based on the data passed in. It also promotes loose-coupling. It depends on the interface or abstract class rather than a concrete class.

Cons

The factory class itself handles making objects. Thus, making it hard to mock that particular object. Factory classes may go bigger and difficult to maintain.

Conclusion

Use a factory pattern when dealing with the creation of many similar objects. If your requirements don’t include the creation of multiple objects. Then using it is not advised. It’s always good to have a concise factory rather than bloating it with all kinds of stuff.

If you have any questions please feel free to leave them in the comment section below.

Author: Aaqib Hussain

Aaqib is an enthusiastic programmer with the love of Swift and anything that looks like Swift i.e Kotlin. He loves writing code in Swift, and exploring new technology and platforms. He likes to listen to old music. When he is not writing code, he’s probably spend his time watching movies, tv-shows or anime, or either doing some research for writing the next article. He started Kode Snippets in 2015.

Be First to Comment

Leave a Reply

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