File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff 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
You can’t perform that action at this time.
0 commit comments