Abstract Factory Design Pattern in Kotlin and Java — Made Easy and Simple
What is an Abstract Factory?
The Abstract Factory Design Pattern is a Creational Pattern that provides an interface for creating families of related or dependent objects without specifying their concrete classes. An example of this would be a CycleFactory
that produces Bicycle
‘s and Tricycle
‘s.
How to create an Abstract Factory in Java
First lets do some setup. Declare a Cycle
abstract class with abstract functions color()
and wheelCount()
, then add a ride()
function that will print information of the object.
Then lets declare subclasses of Cycle
which are Bicycle
and Tricycle
and also some concrete implementations of Bicycle
and Tricycle
.
The Abstract Factory (CycleFactory)
Next let’s define our Abstract Factory. We declare an interface CycleFactory
that will define its purpose as providing both Bicycle
and Tricycle
classes. Bicycle
and Tricycle
are related objects as they both inherit Cycle
.
Next lets define two subclasses of CycleFactory
which are RedCycleFactory
and BlueCycleFactory
.
Lastly, let’s use our new Abstract Factories!
How to create an Abstract Factory in Kotlin
Following the same pattern above, here is the Kotlin equivalent.
That’s it, super simple! You can find the example repository here! Follow me for more coding made simple content!
Want to learn about other Creational design patterns? Here are some others: