-
Notifications
You must be signed in to change notification settings - Fork 109
/
State.kt
90 lines (75 loc) · 2.46 KB
/
State.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package design_patterns
/**
*
* State is a behavioral design pattern that controls changes in the behavior of an object
*
* when its internal state changes
*
*/
// the common interface for all states
interface CocaColaState {
fun insertDollar() : Boolean
fun takeBackDollar() : Boolean
fun pressButton(numberOfDrinks: Int) : Boolean
}
// we don't have drinks in the machine
class EmptyCocaColaState : CocaColaState {
override fun insertDollar() = false
override fun takeBackDollar() = false
override fun pressButton(numberOfDrinks: Int) = false
override fun toString(): String = "EmptyCocaColaState"
}
// we have drinks, but we don't have a dollar in the machine
class NoDollarCocaColaState(private val machine: CocaColaMachine) : CocaColaState {
override fun insertDollar(): Boolean {
machine.setState(HaveDollarCocaColaState(machine))
return true
}
override fun takeBackDollar() = false
override fun pressButton(numberOfDrinks: Int) = false
override fun toString(): String = "NoDollarCocaColaState"
}
// we have a dollar in the machine
class HaveDollarCocaColaState(private val machine: CocaColaMachine) : CocaColaState {
override fun insertDollar() = false
override fun takeBackDollar(): Boolean {
machine.setState(NoDollarCocaColaState(machine))
return true
}
override fun pressButton(numberOfDrinks: Int): Boolean {
if (numberOfDrinks == 1) {
machine.setState(EmptyCocaColaState())
} else {
machine.setState(NoDollarCocaColaState(machine))
}
return true
}
override fun toString(): String = "HaveDollarCocaColaState"
}
// CocaColaMachine switches between states
class CocaColaMachine {
private var numberOfDrinks = 3
private var state: CocaColaState = NoDollarCocaColaState(this)
val currentState: String
get() = state.toString()
fun insertDollar() = state.insertDollar()
fun takeBackDollar() = state.takeBackDollar()
fun pressButton(): Boolean {
val isSuccess = state.pressButton(numberOfDrinks)
if (isSuccess) {
numberOfDrinks -= 1
}
return isSuccess
}
fun loadDrinks(count: Int) {
numberOfDrinks += count
if (numberOfDrinks > 0) {
setState(NoDollarCocaColaState(this))
} else {
setState(EmptyCocaColaState())
}
}
fun setState(newState: CocaColaState) {
state = newState
}
}