32

Factory Pattern in Kotlin

 5 years ago
source link: https://www.tuicool.com/articles/hit/UJ7riuU
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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:

IvAvIzJ.png!web

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

3AfIV3e.png!web

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.

jimYfqq.png!web

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."

b6N3eqb.png!web

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

22qQZji.png!web

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK