Common Design Patterns in Kotlin: Singleton, Factory, Builder, Prototype, Decorator, Strategy, Template Method, and Observer
This article introduces several classic design patterns—Singleton, Factory, Builder, Prototype, Decorator, Strategy, Template Method, and Observer—showing how they can be implemented concisely in Kotlin with code examples, while also explaining the underlying language features such as object declarations, companion objects, delegation, lazy initialization, and higher‑order functions.
Android developers are familiar with design patterns, and Kotlin provides a concise, expressive way to implement them. This article reviews common patterns and demonstrates Kotlin‑specific language features that simplify their usage.
1. Singleton pattern – The eager (饿汉) version is shown in both Java and Kotlin, where Kotlin’s object SingletonK { fun doTest() { println("test singleton kotlin") } } creates a singleton automatically. The article also decompiles the Kotlin singleton to Java bytecode and shows how to access it from Java via SingletonK.INSTANCE.doTest() . The double‑checked locking (DCL) version uses by lazy(LazyThreadSafetyMode.SYNCHRONIZED) in Kotlin: class SingletonDubbleCheckKotlin private constructor() { companion object { val instance: SingletonDubbleCheckKotlin by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { SingletonDubbleCheckKotlin() } } } , illustrating the companion object and property delegation.
2. Factory pattern – The static factory method (SFM) is implemented with a Kotlin companion object : class FruitFactory { companion object { fun getApple() = AppleInKotlin(5.0f) fun getBanana() = BananaInKotlin(8.0f) } } . The article then shows the factory‑method variant using an interface AbsFruitFactory and concrete factories, followed by an extension‑function approach that adds new product creators without modifying the factory class.
3. Builder pattern – Two Kotlin techniques are presented: (a) default parameters in the primary constructor, e.g., class Car(val color: String = "black", val factory: String = "Audi") , and (b) the apply extension function for mutable objects: val newCar = Car().apply { factory = "BMW"; color = "red" } . The source of apply is also displayed.
4. Prototype pattern – Kotlin data classes provide a built‑in copy method. Example: data class Document(val text: String, val imageList: Array ) val doc2 = doc1.copy(text = "bbbbb") creates a shallow copy with modified fields.
5. Decorator pattern – Two approaches are covered: (a) using extension functions to add behavior without a separate decorator class, and (b) class delegation with the by keyword: class RedShapeKotlin(val shape: Shape) : Shape by shape { override fun draw() { println("with red color by "); shape.draw() } } . The article explains when each method is appropriate.
6. Strategy pattern – Demonstrated with higher‑order functions: class Customer(val discount: (Int) -> Int) { fun calculate(money: Int) = discount(money) } and concrete discount functions such as fun fullDiscount(money: Int) = if (money > 200) money - 100 else money .
7. Template method – Implemented by passing a lambda representing the varying step: class OnlineShopping { fun submitOrder(pay: () -> Unit) { calculatePrice(); pay(); sendHome() } } , then calling shopping.submitOrder { weixinPay() } or { zfbPay() } .
8. Observer pattern – The Java version uses Observable and Observer . The Kotlin version leverages Delegates.observable to react to property changes: var vid: Int by Delegates.observable(0) { _, old, new -> observers.forEach { it.update("${it.name}_$new") } } . The article also shows the underlying implementation of observable and ObservableProperty .
In summary, the article demonstrates how Kotlin’s language features—object declarations, companion objects, delegation, lazy properties, extension functions, default arguments, and higher‑order functions—make classic design patterns more concise and expressive, helping developers write cleaner, less boilerplate code.
Sohu Tech Products
A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.