Skip to content

Commit a5792e0

Browse files
committed
Added State pattern
1 parent cfb60d8 commit a5792e0

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

README.markdown

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -345,6 +345,51 @@ tuple.z
345345
##Memento
346346
##Observer
347347
##State
348+
349+
```swift
350+
class Context {
351+
private var state: State = UnauthorizedState()
352+
func changeStateToAuthorized(#userId: String) {
353+
state = AuthorizedState(userId: userId)
354+
}
355+
func changeStateToUnauthorized() {
356+
state = UnauthorizedState()
357+
}
358+
var isAuthorized: Bool {
359+
get { return state.isAuthorized(self) }
360+
}
361+
var userId: String? {
362+
get { return state.userId(self) }
363+
}
364+
}
365+
366+
protocol State {
367+
func isAuthorized(context: Context) -> Bool
368+
func userId(context: Context) -> String?
369+
}
370+
371+
class UnauthorizedState: State {
372+
func isAuthorized(context: Context) -> Bool { return false }
373+
func userId(context: Context) -> String? { return nil }
374+
}
375+
376+
class AuthorizedState: State {
377+
let userId: String
378+
init(userId: String) { self.userId = userId }
379+
func isAuthorized(context: Context) -> Bool { return true }
380+
func userId(context: Context) -> String? { return userId }
381+
}
382+
```
383+
**Usage:**
384+
```swift
385+
let c = Context()
386+
println("\(c.isAuthorized), \(c.userId)")
387+
c.changeStateToAuthorized(userId: "admin")
388+
println("\(c.isAuthorized), \(c.userId)")
389+
c.changeStateToUnauthorized()
390+
println("\(c.isAuthorized), \(c.userId)")
391+
```
392+
348393
##Strategy
349394

350395
```swift

0 commit comments

Comments
 (0)