0
0
Kotlinprogramming~3 mins

Why Factory pattern with companion objects in Kotlin? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could create objects with a simple call, no matter how many types you add later?

The Scenario

Imagine you want to create different types of vehicles in your app, like cars and bikes. You write separate code everywhere to make each one, repeating similar steps again and again.

The Problem

This manual way is slow and messy. If you want to add a new vehicle type, you must change many parts of your code. It's easy to make mistakes and hard to keep track of all the creation details.

The Solution

The factory pattern with companion objects lets you centralize the creation logic inside the class itself. You just call a simple method to get the right vehicle, and the class handles the details. This keeps your code clean and easy to update.

Before vs After
Before
val car = Car("red")
val bike = Bike("blue")
After
val car = Vehicle.create("car", "red")
val bike = Vehicle.create("bike", "blue")
What It Enables

This pattern makes your code flexible and easy to extend, so you can add new types without changing the rest of your program.

Real Life Example

Think of a game where you create different characters. Using a factory with companion objects, you just ask for a character type, and the game gives you the right one without extra hassle.

Key Takeaways

Manual creation is repetitive and error-prone.

Factory pattern centralizes object creation inside the class.

Companion objects make it easy to call factory methods without extra classes.