Skip to content

Commit 19ddfa4

Browse files
author
Sebastian Boldt
committed
added example code for state pattern
1 parent f3d75a5 commit 19ddfa4

File tree

4 files changed

+48
-1
lines changed

4 files changed

+48
-1
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
//: [Previous](@previous)
2+
3+
import Foundation
4+
5+
protocol State {
6+
var isAuthorized: Bool { get }
7+
}
8+
9+
final class UserContext {
10+
private var userId: String
11+
private var state: State = UnauthorizedState()
12+
13+
init(userID: String) {
14+
self.userId = userId
15+
}
16+
17+
var isAuthorized: Bool {
18+
self.state.isAuthorized
19+
}
20+
public func changeToAuthorizedState() {
21+
self.state = AuthorizedState()
22+
}
23+
24+
public func changeToUnauthorizedState() {
25+
self.state = UnauthorizedState()
26+
}
27+
}
28+
29+
struct AuthorizedState: State {
30+
var isAuthorized: Bool {
31+
return true
32+
}
33+
}
34+
35+
struct UnauthorizedState: State {
36+
var isAuthorized: Bool {
37+
return false
38+
}
39+
}
40+
41+
var context = UserContext(userID: UUID().uuidString)
42+
context.changeToAuthorizedState()
43+
context.isAuthorized
44+
45+
//: [Next](@next)

β€ŽBehavioral.playground/contents.xcplayground

+2-1
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,9 @@
66
<page name='Iterator'/>
77
<page name='Strategy'/>
88
<page name='Mediator'/>
9-
<page name='Observer'/>
109
<page name='Visitor'/>
1110
<page name='Memento'/>
11+
<page name='Observer'/>
12+
<page name='State'/>
1213
</pages>
1314
</playground>

β€ŽStructural.playground/Pages/Flyweight.xcplaygroundpage/Contents.swift

+1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
//: [Previous](@previous)
22

33
import Foundation
4+
import CoreGraphics
45

56
protocol Soldier {
67
func render(from location: CGPoint, to newLocation: CGPoint)

0 commit comments

Comments
Β (0)