From 23b9f24503130f1f3d29f0ab7a33ea3a08e0c064 Mon Sep 17 00:00:00 2001 From: Allan Wang Date: Tue, 26 Dec 2017 05:05:37 -0500 Subject: Create flyweight (#118) --- .../kotlin/ca/allanwang/kau/kotlin/FlyWeight.kt | 40 ++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 core/src/main/kotlin/ca/allanwang/kau/kotlin/FlyWeight.kt (limited to 'core') diff --git a/core/src/main/kotlin/ca/allanwang/kau/kotlin/FlyWeight.kt b/core/src/main/kotlin/ca/allanwang/kau/kotlin/FlyWeight.kt new file mode 100644 index 0000000..03e98d2 --- /dev/null +++ b/core/src/main/kotlin/ca/allanwang/kau/kotlin/FlyWeight.kt @@ -0,0 +1,40 @@ +package ca.allanwang.kau.kotlin + +/** + * Created by Allan Wang on 26/12/17. + * + * Kotlin implementation of a flyweight design pattern + * Values inside the map will be returned directly + * Otherwise, it will be created with the supplier, saved, and returned + * In the event a default is provided, the default takes precedence + */ +fun flyweight(creator: (K) -> V) = FlyWeight(creator) + +class FlyWeight(private val creator: (key: K) -> V) : Map { + + private val map = mutableMapOf() + + override val entries: Set> + get() = map.entries + override val keys: Set + get() = map.keys + override val size: Int + get() = map.size + override val values: Collection + get() = map.values + + override fun containsKey(key: K) = map.containsKey(key) + + override fun containsValue(value: V) = map.containsValue(value) + + override fun getOrDefault(key: K, defaultValue: V) = map.getOrDefault(key, defaultValue) + + override fun isEmpty() = map.isEmpty() + + override fun get(key: K): V { + if (!map.containsKey(key)) + map.put(key, creator(key)) + return map[key]!! + } + +} \ No newline at end of file -- cgit v1.2.3