Abstract Factory Design Pattern in Kotlin and Java — Made Easy and Simple

Eric Diaz
2 min readJul 15, 2022
Abstract Factory Design Pattern — for making Bikes in Kotlin and Java

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.

Abstract Factory Design Pattern in Java — The setup

Then lets declare subclasses of Cycle which are Bicycle and Tricycle and also some concrete implementations of Bicycle and Tricycle .

Abstract Factory Design Pattern in Java — The setup

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 .

Abstract Factory Design Pattern in Java — The Abstract Factory

Next lets define two subclasses of CycleFactory which are RedCycleFactory and BlueCycleFactory .

Abstract Factory Design Pattern in Java— The Abstract Factory Implementations

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.

Abstract Factory Design Pattern in Kotlin — The Abstract Factory

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:

--

--