Factory Pattern in Kotlin

DZone 's Guide to

Factory Pattern in Kotlin

Want to learn more about the factory design pattern in Kotlin? Check out this post where we will explore factory pattern with a simple example.

· Java Zone ·
Free Resource

Kotlin is one of the most competitive JVM languages. It has been created by JetBrains and it keeps rising. Google recently endorsed Kotlin as an officially supported language for Android development, enhancing Kotlin’s profile, but it also applies to server-side development. For example, Kotlin works smoothly with Spring Boot.

The factory method pattern is one of the creational patterns of the well known “Gang of Four” design patterns. In the factory pattern, we can create objects by calling a factory method rather by calling a constructor. As a result, we don’t need to specify the class of the created object. It provides different approaches to code for interface rather than implementation, and it makes our code less coupled and more extendable.

This scenario is an implementation of creating Book objects and accessing their methods with the factory pattern. 

First, we will create a Book interface and declare three methods that represent actions for the books:

Image title

Next, create a Genre Enum with two instances "SCIENCE" and "LITERATURE:"

Image title

After that, create a BookFactory class for creating objects using the Kotlin companion object. Every class can implement a companion object, which is common to all instances of that class. It is similar to static fields in Java. So, we don’t need to instantiate the BookFactory at all. We implemented a createBook method with Genre as an argument and create interface method implementations for each instance.

Image title

At last, implement the main method, which we call createBook from BookFactory, and we are able to dynamically get Book by passing the type in method, for example, “SCIENCE."

Image title

If we run main, we get the output below at console in IntelliJ:

Image title

I hope this post will help you get started with the factory method pattern in Kotlin. Happy coding!

factory design patterns ,factory pattern ,java ,jvm ,kotlin ,tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}