forked from dbacinski/Design-Patterns-In-Kotlin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AbstractFactory.kt
45 lines (32 loc) · 1.05 KB
/
AbstractFactory.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
//Based on: http://stackoverflow.com/a/13030163/361832
interface Plant
class OrangePlant : Plant
class ApplePlant : Plant
abstract class PlantFactory {
abstract fun makePlant(): Plant
companion object {
inline fun <reified T : Plant> createFactory(): PlantFactory =
when (T::class) {
OrangePlant::class -> OrangeFactory()
ApplePlant::class -> AppleFactory()
else -> throw IllegalArgumentException()
}
}
}
class AppleFactory : PlantFactory() {
override fun makePlant(): Plant = ApplePlant()
}
class OrangeFactory : PlantFactory() {
override fun makePlant(): Plant = OrangePlant()
}
class AbstractFactoryTest {
@Test
fun `Abstract Factory`() {
val plantFactory = PlantFactory.createFactory<OrangePlant>()
val plant = plantFactory.makePlant()
println("Created plant: $plant")
assertThat(plant).isInstanceOf(OrangePlant::class.java)
}
}