Skip to content
Tutorials Center
My learning

Topics

Lesson 76 of 134 ยท Idiomatic Kotlin

Design Patterns in Kotlin

Learn how classic design patterns look in Kotlin: singleton with object, factories, builders, observer, strategy and decorator, often shorter than in Java, with runnable code.

A design pattern is a named, well-known solution to a problem that keeps coming back in software: "I need exactly one of these", "I want to build an object step by step", "I need to tell several parts of the program that something changed". Books on patterns were written for languages where each of these solutions needed a page of boilerplate.

Kotlin has language features that absorb many patterns: object declarations, companion objects, default arguments, function types, delegation and sealed classes. A pattern that needs three classes and an interface in Java often becomes a few lines. This lesson walks through six patterns you will meet constantly and shows the Kotlin way to write each one. You should know objects and companions, lambdas and delegation.

Singleton: just write object

A singleton guarantees that only one instance of a class exists. In Java you hide the constructor, keep a static field and worry about thread safety. In Kotlin the declaration object Name { ... } is the whole pattern: the instance is created lazily, on first access, in a thread-safe way.

Kotlin A singleton registry

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The init message appears after start of main, because the object is created on first use, not at program start. Both accesses go to the same instance, which is why === prints true.

A singleton is global state. It is convenient, but every function that reads it has a hidden dependency that is hard to replace in tests. Prefer passing dependencies as constructor parameters, and keep object for things that are truly stateless or process-wide, such as a clock, a logger or a set of constants.

Factory: named functions in a companion

A factory creates objects without making the caller pick the exact class or constructor. Kotlin gives you two natural tools: functions in a companion object, and top-level functions that return an interface type. Combine them with a sealed interface and when and the compiler checks that every case is handled.

Kotlin A companion factory and a type-choosing factory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Circle and Rect are private to the file, so no caller can depend on them. If you later add a cache or a third shape, only the factory changes. In the second half, the private constructor forces everybody through named factory functions, which read better than overloaded constructors.

Builder: default arguments first, builders second

The builder pattern exists to create objects with many optional settings without a constructor that has twelve parameters. In Kotlin, default and named arguments solve most of this already, so reach for them first:

Kotlin
data class Request(
    val url: String,
    val method: String = "GET",
    val headers: Map<String, String> = emptyMap(),
    val timeoutMs: Int = 5_000,
)

val request = Request("https://example.com", timeoutMs = 1_000)

You only need a real builder when construction has several steps, when settings depend on each other, or when you want the nice nested syntax of a type-safe DSL. The lambda-with-receiver form gives you that with very little code:

Kotlin A builder with a lambda receiver

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The mutable builder lives only inside the lambda. What you get back is an immutable Pizza, and build() is the single place where the rules are checked.

Observer: lambdas instead of listener interfaces

The observer pattern lets one object (the subject) notify others (the observers) when something happens. Java traditionally needs a listener interface plus an implementing class. Kotlin function types let an observer be just a lambda:

Kotlin An observable value with lambda observers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Delegates.observable runs your block after every assignment, which makes the notification automatic. For streams of changes in real programs, look at StateFlow and SharedFlow, which are the coroutine-based version of the same idea and handle threads and cancellation for you.

Strategy: pass the behavior as a function

The strategy pattern swaps an algorithm at run time: sort ascending or descending, apply a discount or not. Classically that means an interface and one class per algorithm. A strategy is just a function, and Kotlin treats functions as values:

Kotlin Strategies as function values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

If a strategy needs its own state or several methods, use an interface after all, and then a fun interface still lets callers pass a lambda. The standard library uses this everywhere: sortedWith(comparator) and sortedBy { } are strategies.

Decorator: delegation with by

A decorator wraps an object and adds behavior while keeping the same interface. Written by hand, you forward every method of the interface to the wrapped object. Kotlin's by keyword generates that forwarding for you, so you override only what you change:

Kotlin A logging decorator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

You can stack decorators (Logging(Caching(Memory()))) because each one is a Storage. Without by, a decorator over an interface with ten methods would need ten forwarding functions.

Choosing: patterns are tools, not goals

Do not start from a pattern and look for a place to use it. Start from the problem. If object, a default argument, a lambda or by solves it, you have already applied the pattern, with no extra classes.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When is a Kotlin object declaration (object Name) created?

    An object declaration is a lazily created singleton. The first access initializes it safely, and every later access returns the same instance.
  2. 2. Which Kotlin feature removes most of the need for a classic builder class?

    A constructor with default values and named arguments lets callers set only what they care about. Write a real builder only for multi-step or validated construction.
  3. 3. How can you express the strategy pattern most simply in Kotlin?

    A strategy is a swappable piece of behavior, and Kotlin functions are values. Interfaces are only needed when the strategy has state or several methods.
  4. 4. What does class LoggingStorage(private val inner: Storage) : Storage by inner do?

    Class delegation with by makes the compiler generate every interface method as a call to the wrapped object. That is what makes decorators short.

Summary

  • object is the singleton pattern in one keyword: lazy, thread-safe and unique. Keep it for stateless or process-wide things.
  • Factories are named functions in a companion object, or top-level functions returning an interface; combine with sealed types and when.
  • Default and named arguments cover most builders; use a lambda-with-receiver builder for multi-step or validated construction.
  • Observers can be plain lambdas, and Delegates.observable or StateFlow automate the notification.
  • A strategy is a function value, and a decorator is a wrapper written with by delegation.

Next: Context Parameters