An example of a flyweight pattern in Kotlin.
Table of contents for design patterns in Kotlin
In computer programming, flyweight is a software design pattern. A flyweight is an object that minimizes memory usage by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory. Often some parts of the object state can be shared, and it is common practice to hold them in external data structures and pass them to the objects temporarily when they are used. Wikipedia
Example:
Ingredient
data class Ingredient(val name: String) {
companion object {
private val cache: WeakHashMap<String, Ingredient> = WeakHashMap<String, Ingredient>()
fun intern(name: String): Ingredient {
synchronized(cache) { return cache.computeIfAbsent(name) { Ingredient(name) } }
}
fun ingredientInCache(): Int {
synchronized(cache) { return cache.size }
}
}
}
Recipe
interface Recipe {
fun make()
companion object {
fun of(ingredients : List<Pair<String, Int>>) = object: Recipe {
override fun make(){
println("Make recipe")
ingredients.forEach {
println("${Ingredient.intern(it.first)}: ${it.second} gram")
}
}
}
}
}
Kitchen
class Kitchen {
private val recipes = mutableListOf<Recipe>()
fun addRecipes(ingredients: List<Pair<String, Int>>) {
recipes.add(Recipe.of(ingredients))
}
fun make() {
recipes.forEach { it.make() }
}
}
Usage
fun main() {
val kitchen = Kitchen()
kitchen.addRecipes(listOf(
"salt" to 10,
"sugar" to 20,
"pepper" to 20
))
kitchen.addRecipes(listOf(
"salt" to 10,
"sugar" to 20,
"pepper" to 20,
"flour" to 200
))
kitchen.make()
println("${Ingredient.ingredientInCache()}")
}
Result
Make recipe
Ingredient(name=salt): 10 gram
Ingredient(name=sugar): 20 gram
Ingredient(name=pepper): 20 gram
Make recipe
Ingredient(name=salt): 10 gram
Ingredient(name=sugar): 20 gram
Ingredient(name=pepper): 20 gram
Ingredient(name=flour): 200 gram
4