Reader small image

You're reading from  Kotlin Design Patterns and Best Practices - Third Edition

Product typeBook
Published inApr 2024
PublisherPackt
ISBN-139781805127765
Edition3rd Edition
Right arrow
Author (1)
Alexey Soshin
Alexey Soshin
author image
Alexey Soshin

Alexey Soshin is a software architect with 18 years of experience in the industry. He started exploring Kotlin when Kotlin was still in beta, and since then has been a big enthusiast of the language. He's a conference speaker, published writer, and the author of a video course titled Pragmatic System Design
Read more about Alexey Soshin

Right arrow

Working with Creational Patterns

In this chapter, we will explore how classic creational patterns are implemented using Kotlin. These patterns focus on when and how you create objects. For each design pattern, we will discuss its purpose and how Kotlin facilitates its implementation.

The topics covered in this chapter include the following patterns:

  • Singleton
  • Factory Method
  • Abstract Factory
  • Builder
  • Prototype

By mastering these design patterns, you will improve your ability to manage objects, adapt to changes, and write maintainable code.

Before we proceed, it’s important to acknowledge that not all of the design patterns described in this and subsequent chapters may be useful to you. However, it is still valuable to be thorough and cover all the design patterns outlined in the original Gang of Four book, as they are still relevant today.

As we explore each design pattern, I will also introduce some essential Kotlin syntax...

Technical requirements

There are no additional technical requirements above those listed in the previous chapter.

You can find the code files for this chapter on GitHub at https://github.com/PacktPublishing/Kotlin-Design-Patterns-and-Best-Practices_Third-Edition/tree/main/Chapter02.

Singleton

The Singleton pattern is widely recognized and often referred to, even by those who are not fans of using design patterns.

At one point, the Singleton pattern was considered an “anti-pattern” precisely because of its overwhelming popularity. The logic was this: if something is everywhere, it can’t be that good. In the Spring Framework, the Singleton scope is indeed the default for its components, which are commonly referred to as “beans.” This approach is similarly adopted in the Koin framework, illustrating the widespread acceptance and use of the Singleton scope in modern software development.

For those encountering this pattern for the first time, let’s explore what it’s all about. In the previous chapter, we already discussed classes and data structures in Kotlin.

Typically, when you have a class, you can create multiple instances of it. For instance, imagine we are both asked to list our favorite movies.

...

Factory Method

The Factory Method design pattern focuses on the creation of objects. However, you might wonder why we need a method for object creation when constructors already serve that purpose. The answer lies in the limitations of constructors.

To illustrate this, let’s consider the example of building a chess game. Suppose we want to allow players to save the game state into a text file and later restore the game from that position.

Since the size of the chessboard is predetermined, we only need to record the position and type of each piece. We can use algebraic notation for this purpose. For instance, the Queen piece at C3 will be stored in the file as qc3, the pawn piece at A8 as pa8, and so on.

Now, let’s assume that we have already read this file into a list of strings. This application of the Singleton design pattern, as we discussed earlier, would be an excellent fit.

Given the list of notations, our goal is to populate the chessboard with...

Abstract Factory

The Abstract Factory design pattern is often misunderstood and considered complex, but it is actually quite simple. If you already understand the Factory Method pattern, grasping the Abstract Factory pattern will be easy because it builds upon the concepts of factory methods.

In essence, the Abstract Factory pattern is a factory of factories. It involves a factory that can create multiple related classes, making it a class that encapsulates several factory methods.

Now, you might be wondering about the practical use of this design pattern. In real-world scenarios, the Abstract Factory pattern is commonly employed in frameworks and libraries that rely on configuration files for their setup. One such example is the Spring Framework.

To better comprehend how the design pattern works, let’s consider a scenario where we have a server configuration specified in a YAML file:

server:
    port: 8080
    environment: production

Our objective is to...

Builder

The complexity of object creation in programming can vary widely. In some cases, objects are straightforward with just a single constructor, which could be either empty or parameterized. However, there are scenarios where object creation is intricate, involving multiple parameters. While the Static Factory Method design pattern offers an alternative approach to constructors, it primarily addresses simpler object creation. For more complex scenarios, we turn to the Builder design pattern.

This pattern is particularly useful when dealing with objects that require a multitude of parameters, some of which might be optional. It offers a clear and flexible way to construct such complex objects. To illustrate this, let’s consider the example of designing a class to represent an email.

In this case, we won’t examine the actual mechanics of sending emails but will focus on the nuances of constructing an email object that could potentially include various fields...

Prototype

The Prototype design pattern focuses on customization and the creation of objects that are similar but have slight variations. To gain a better understanding, let’s examine an example.

Consider a system that handles user management and permissions. We can represent a user using a data class, which might be structured as follows:

data class User(
    val name: String,
    val role: Role,
    val permissions: Set<String>,
) {
    fun hasPermission(permission: String) = permission in permissions
}

Each user must have a role, and each role has a set of permissions.

We’ll describe a role as an enum class:

enum class Role {
    ADMIN,
    SUPER_ADMIN,
    REGULAR_USER
}

Enum classes offer a convenient method for representing a collection of constants. This approach is advantageous compared to using strings to represent roles, as it allows for compile-time checks ensuring the existence of such objects. Additionally, using an enum allows...

Summary

In this chapter, we learned about creational design patterns and how they help us manage object creation.

We started by using the object keyword to make a class with only one instance. Then, we discussed using a companion object for Static Factory Methods, which lets subclasses define which kind of object to create.

After that, we talked about smart casts, which make it easier to work with different types of objects. We applied them in the Abstract Factory design pattern to create groups of related objects.

Next, we explored the Builder design pattern, where we saw how to create complex objects step by step. We also found out that functions can have default values for their inputs, and we can use names for the inputs instead of just their positions.

Finally, we looked at the copy() function of data classes. This is like making a clone of an object, and it helps us when using the Prototype design pattern to make similar objects with small changes.

The interesting...

Questions

  1. Name two uses for the object keyword we learned about in this chapter.
  2. What is the apply() function used for?
  3. Provide one example of a Static Factory Method.

Learn more on Discord

Join our community’s Discord space for discussions with the author and other readers:

https://discord.com/invite/xQ7vVN4XSc

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Kotlin Design Patterns and Best Practices - Third Edition
Published in: Apr 2024Publisher: PacktISBN-13: 9781805127765
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Alexey Soshin

Alexey Soshin is a software architect with 18 years of experience in the industry. He started exploring Kotlin when Kotlin was still in beta, and since then has been a big enthusiast of the language. He's a conference speaker, published writer, and the author of a video course titled Pragmatic System Design
Read more about Alexey Soshin