Factory Method Design Pattern in Kotlin and Java — Made Easy and Simple
What is a Factory?
The Factory Method design pattern works by defining an interface for creating an object, but let subclasses decide which class to instantiate. A Factory is responsible for creating objects of a certain type and its subclasses.
How to create a Factory in Java
Creating a Factory in Java is simple! For this example, we will be implementing a Factory that creates cars based on the manufacturer. In other words, we will implement a CarFactory
.
Start with declaring your Car
class and some subclasses that we eventually want to produce through the Factory.
There are many ways to evaluate how a Factory will produce the desired type subclass. In this example, we will have the the Factory produce Car
s based on the their manufacturer, so lets declare a CarManufacturer
class with some subclasses.
Lastly, Let’s create the CarFactory
. The Factory will contain a producing function that will return a Car
based on the CarManufacturer
.
Now lets see it in action!
How to create a Factory in Kotlin
Following the same pattern above, this is what the Kotlin version looks like.
That’s it, super simple! You can find the example repository here! Follow me for more coding made simple content!
Bonus Content! Are you interested on how this CarFactory
can be made better? See how the implementation is improved in Improve your Factory Method Implementation.
Want to learn about other Creational design patterns? Here are some others: