Factory Pattern in Kotlin
Factory Pattern helps us to avoid code duplication by centralizing the process of creating objects. Factory Pattern says that define an interface or abstract class to create an object and allow the subclasses to decide which class to instantiate.
Why We Use This Pattern?
The simple answer is expandability :) We tell the factory class which object we wanna create and the factory class creates the object for us without we know the details of the object creation. On the other hand, the factory handles any change related to object creation.
Let’s apply the Factory Pattern
Imagine that you’re developing a holiday agency application. The first version of your app supports a cultural holiday. After a while, your agency becomes very popular so your agency grows. Now you need to support a cruise holiday for new customers! How can we do that by applying the Factory Pattern?..
UML for The Factory Pattern
Explanation
Culture
and Cruise
classes implement the Holiday
interface, which has a method called holidayInfo
. Each class implements this method differently. The createHoliday
method uses different agencies(CruiseHolidayAgency, CultureHolidayAgency) to create a holiday by request.
A code that uses the createHoliday
doesn’t see a difference on Holiday
object that returned by the HolidayFactory
and only know that all holiday objects have the holidayInfo
method.