|
1 | | -# Kotlin OOP and FP Design Patterns |
| 1 | +Kotlin OOP and FP Design Patterns |
| 2 | +============= |
| 3 | +[](https://travis-ci.org/CloudCoders/Design-Patterns) |
| 4 | +[](http://kotlinlang.org/) |
2 | 5 |
|
3 | 6 | ## Index |
4 | 7 |
|
|
12 | 15 | * [ ] [Memento](#memento) |
13 | 16 | * [ ] [Null Object](#null-object) |
14 | 17 | * [x] [Observer](#observer) |
15 | | - * [ ] [State](#state) |
| 18 | + * [x] [State](#state) |
16 | 19 | * [ ] [Template](#template) |
17 | 20 | * [ ] [Visitor](#visitor) |
18 | 21 | * [Creational Patterns](#creational) |
@@ -221,12 +224,57 @@ shop.currentCustomers++ // prints "A new customer entered ..." |
221 | 224 | shop.currentCustomers-- // prints "A customer left ..." |
222 | 225 | ``` |
223 | 226 |
|
224 | | -State |
| 227 | +[State](/src/main/kotlin/oop/State) |
225 | 228 | ------- |
226 | 229 |
|
227 | 230 | > It allows an object to alter its behaviour when its internal state changes. |
228 | 231 |
|
229 | | -**In progress** |
| 232 | +We can use Kotlin's [sealed classes](https://kotlinlang.org/docs/reference/sealed-classes.html) to define a restricted hierarchy so that the current _State_ can only have limited values from a set. |
| 233 | + |
| 234 | +### Example |
| 235 | + |
| 236 | +```kotlin |
| 237 | +interface State { |
| 238 | + fun next(): State |
| 239 | +} |
| 240 | + |
| 241 | +sealed class SemaphoreStates : State { |
| 242 | + object Red : SemaphoreStates() { |
| 243 | + override fun next() = Green |
| 244 | + } |
| 245 | + |
| 246 | + object Green : SemaphoreStates() { |
| 247 | + override fun next() = Yellow |
| 248 | + } |
| 249 | + |
| 250 | + object Yellow : SemaphoreStates() { |
| 251 | + override fun next() = Red |
| 252 | + } |
| 253 | +} |
| 254 | + |
| 255 | +class Semaphore(startingState: State = SemaphoreStates.Red) { |
| 256 | + var state = startingState |
| 257 | + private set |
| 258 | + |
| 259 | + fun nextLight() { |
| 260 | + state = state.next() |
| 261 | + } |
| 262 | +} |
| 263 | +``` |
| 264 | + |
| 265 | +### Usage |
| 266 | + |
| 267 | +```kotlin |
| 268 | +fun Semaphore.canICross() = this.state is SemaphoreStates.Green |
| 269 | + |
| 270 | +val semaphore = Semaphore() |
| 271 | + |
| 272 | +println(semaphore.canICross()) // false |
| 273 | + |
| 274 | +semaphore.nextLight() |
| 275 | + |
| 276 | +println(semaphore.canICross()) // true |
| 277 | +``` |
230 | 278 |
|
231 | 279 | [Strategy](/src/main/kotlin/oop/Strategy) |
232 | 280 | --------- |
|
0 commit comments