Skip to content

Commit efabcae

Browse files
committed
A little less boring. Added proper observer.
1 parent f94a3d9 commit efabcae

17 files changed

+311
-286
lines changed

Design-Patterns.playground.zip

243 Bytes
Binary file not shown.
Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
1-
struct Cart<T> {
2-
let items: [T]
1+
struct NovellasCollection<T> {
2+
let novellas: [T]
33
}
44

5-
extension Cart: SequenceType {
5+
extension NovellasCollection: SequenceType {
66
typealias Generator = GeneratorOf<T>
77

88
func generate() -> GeneratorOf<T> {
99
var i = 0
10-
return GeneratorOf { return i >= self.items.count ? nil : self.items[i++] }
10+
return GeneratorOf { return i >= self.novellas.count ? nil : self.novellas[i++] }
1111
}
1212
}
Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
let cart = Cart(items: ["foo", "bar", "baz"])
1+
let greatNovellas = NovellasCollection(novellas:["Mist"])
22

3-
for item in cart {
4-
println(item)
3+
for novella in greatNovellas {
4+
println("I've read: \(novella)")
55
}
Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,39 @@
11
typealias Memento = Dictionary<NSObject, AnyObject>
22

3+
let DPMementoKeyChapter = "com.valve.halflife.chapter"
4+
let DPMementoKeyWeapon = "com.valve.halflife.weapon"
5+
let DPMementoGameState = "com.valve.halflife.state"
6+
37
/**
48
* Originator
59
*/
610
class GameState {
7-
var gameLevel: Int = 1
8-
var playerScore: Int = 0
11+
var chapter: String = ""
12+
var weapon: String = ""
913

10-
func saveToMemento() -> Memento {
11-
return ["gameLevel": gameLevel, "playerScore": playerScore]
14+
func toMemento() -> Memento {
15+
return [ DPMementoKeyChapter:chapter, DPMementoKeyWeapon:weapon ]
1216
}
1317

1418
func restoreFromMemento(memento: Memento) {
15-
gameLevel = memento["gameLevel"]! as Int
16-
playerScore = memento["playerScore"]! as Int
19+
chapter = memento[DPMementoKeyChapter] as String? ?? "n/a"
20+
weapon = memento[DPMementoKeyWeapon] as String? ?? "n/a"
1721
}
1822
}
1923

2024
/**
2125
* Caretaker
2226
*/
2327
class CheckPoint {
24-
class func saveState(memento: Memento, keyName: String = "gameState") {
25-
let defaults:NSUserDefaults = NSUserDefaults.standardUserDefaults()
28+
class func saveState(memento: Memento, keyName: String = DPMementoGameState) {
29+
let defaults = NSUserDefaults.standardUserDefaults()
2630
defaults.setObject(memento, forKey: keyName)
2731
defaults.synchronize()
2832
}
2933

30-
class func restorePreviousState(keyName: String = "gameState") -> Memento {
31-
let defaults:NSUserDefaults = NSUserDefaults.standardUserDefaults()
34+
class func restorePreviousState(keyName: String = DPMementoGameState) -> Memento {
35+
let defaults = NSUserDefaults.standardUserDefaults()
3236

33-
return defaults.objectForKey(keyName) as Memento
37+
return defaults.objectForKey(keyName) as Memento! ?? Memento()
3438
}
3539
}
Lines changed: 12 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,20 @@
11
var gameState = GameState()
2-
gameState.gameLevel = 2
3-
gameState.playerScore = 200
4-
5-
// Saves state: {gameLevel 2 playerScore 200}
6-
CheckPoint.saveState(gameState.saveToMemento())
7-
8-
gameState.gameLevel = 3
9-
gameState.gameLevel = 250
10-
11-
// Restores state: {gameLevel 2 playerScore 200}
122
gameState.restoreFromMemento(CheckPoint.restorePreviousState())
133

14-
gameState.gameLevel = 4
4+
gameState.chapter = "Black Mesa Inbound"
5+
gameState.weapon = "Crowbar"
6+
CheckPoint.saveState(gameState.toMemento())
157

16-
// Saves state - gameState2: {gameLevel 4 playerScore 200}
17-
CheckPoint.saveState(gameState.saveToMemento(), keyName: "gameState2")
8+
gameState.chapter = "Anomalous Materials"
9+
gameState.weapon = "Glock 17"
10+
gameState.restoreFromMemento(CheckPoint.restorePreviousState())
1811

19-
gameState.gameLevel = 5
20-
gameState.playerScore = 300
12+
gameState.chapter = "Unforeseen Consequences"
13+
gameState.weapon = "MP5"
14+
CheckPoint.saveState(gameState.toMemento(), keyName: "gameState2")
2115

22-
// Saves state - gameState3: {gameLevel 5 playerScore 300}
23-
CheckPoint.saveState(gameState.saveToMemento(), keyName: "gameState3")
16+
gameState.chapter = "Office Complex"
17+
gameState.weapon = "Crossbow"
18+
CheckPoint.saveState(gameState.toMemento())
2419

25-
// Restores state - gameState2: {gameLevel 4 playerScore 200}
2620
gameState.restoreFromMemento(CheckPoint.restorePreviousState(keyName: "gameState2"))
Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,32 @@
1-
class StepCounter {
2-
var totalSteps: Int = 0 {
3-
4-
willSet(newTotalSteps) {
5-
println("About to set totalSteps to \(newTotalSteps)")
6-
}
1+
protocol PropertyObserver : class {
2+
func willChangePropertyName(propertyName:String, newPropertyValue:AnyObject?)
3+
func didChangePropertyName(propertyName:String, oldPropertyValue:AnyObject?)
4+
}
5+
6+
class TestChambers {
7+
8+
weak var observer:PropertyObserver?
79

10+
var testChamberNumber: Int = 0 {
11+
willSet(newValue) {
12+
observer?.willChangePropertyName("testChamberNumber", newPropertyValue:newValue)
13+
}
814
didSet {
15+
observer?.didChangePropertyName("testChamberNumber", oldPropertyValue:oldValue)
16+
}
17+
}
18+
}
19+
20+
class Observer : PropertyObserver {
21+
func willChangePropertyName(propertyName: String, newPropertyValue: AnyObject?) {
22+
if newPropertyValue as Int? == 1 {
23+
println("Okay. Look. We both said a lot of things that you're going to regret.")
24+
}
25+
}
926

10-
if totalSteps > oldValue {
11-
println("Added \(totalSteps - oldValue) steps")
12-
}
27+
func didChangePropertyName(propertyName: String, oldPropertyValue: AnyObject?) {
28+
if oldPropertyValue as Int? == 0 {
29+
println("Sorry about the mess. I've really let the place go since you killed me.")
1330
}
1431
}
1532
}
Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,4 @@
1-
let stepCounter = StepCounter()
2-
stepCounter.totalSteps = 200
3-
// About to set totalSteps to 200
4-
// Added 200 steps
5-
stepCounter.totalSteps = 360
6-
// About to set totalSteps to 360
7-
// Added 160 steps
8-
stepCounter.totalSteps = 896
9-
// About to set totalSteps to 896
10-
// Added 536 steps
1+
var observerInstance = Observer()
2+
var testChambers = TestChambers()
3+
testChambers.observer = observerInstance
4+
testChambers.testChamberNumber++
Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,27 @@
11
protocol PlanetVisitor {
2-
func visit(planet: PlanetEarth)
3-
func visit(planet: PlanetMars)
4-
func visit(planet: PlanetGliese581C)
2+
func visit(planet: PlanetAlderaan)
3+
func visit(planet: PlanetCoruscant)
4+
func visit(planet: PlanetTatooine)
55
}
66

77
protocol Planet {
88
func accept(visitor: PlanetVisitor)
99
}
1010

11-
class PlanetEarth: Planet {
11+
class PlanetAlderaan: Planet {
1212
func accept(visitor: PlanetVisitor) { visitor.visit(self) }
1313
}
14-
class PlanetMars: Planet {
14+
class PlanetCoruscant: Planet {
1515
func accept(visitor: PlanetVisitor) { visitor.visit(self) }
1616
}
17-
class PlanetGliese581C: Planet {
17+
class PlanetTatooine: Planet {
1818
func accept(visitor: PlanetVisitor) { visitor.visit(self) }
1919
}
2020

2121
class NameVisitor: PlanetVisitor {
2222
var name = ""
2323

24-
func visit(planet: PlanetEarth) { name = "Earth" }
25-
func visit(planet: PlanetMars) { name = "Mars" }
26-
func visit(planet: PlanetGliese581C) { name = "Gliese 581 C" }
24+
func visit(planet: PlanetAlderaan) { name = "Alderaan" }
25+
func visit(planet: PlanetCoruscant) { name = "Coruscant" }
26+
func visit(planet: PlanetTatooine) { name = "Tatooine" }
2727
}

Design-Patterns.playground/section-36.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
let planets: [Planet] = [PlanetEarth(), PlanetMars(), PlanetGliese581C()]
1+
let planets: [Planet] = [PlanetAlderaan(), PlanetCoruscant(), PlanetTatooine()]
22

33
let names = planets.map { (planet: Planet) -> String in
44
let visitor = NameVisitor()
Lines changed: 25 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,45 @@
1-
protocol FileOperationCommand {
2-
init(file: String)
3-
func execute()
1+
protocol DoorCommand {
2+
func execute() -> String
43
}
54

6-
class FileMoveCommand : FileOperationCommand {
7-
let file:String
5+
class OpenCommand : DoorCommand {
6+
let doors:String
87

9-
required init(file: String) {
10-
self.file = file
8+
required init(doors: String) {
9+
self.doors = doors
1110
}
1211

13-
func execute() {
14-
print("\(file) moved")
12+
func execute() -> String {
13+
return "Opened \(doors)"
1514
}
1615
}
1716

18-
class FileDeleteCommand : FileOperationCommand {
19-
let file:String
17+
class CloseCommand : DoorCommand {
18+
let doors:String
2019

21-
required init(file: String) {
22-
self.file = file
20+
required init(doors: String) {
21+
self.doors = doors
2322
}
2423

25-
func execute() {
26-
print("\(file) deleted")
24+
func execute() -> String {
25+
return "Closed \(doors)"
2726
}
2827
}
2928

30-
class FileManager {
31-
let deleteCommand: FileOperationCommand
32-
let moveCommand: FileOperationCommand
29+
class HAL9000DoorsOperations {
30+
let openCommand: DoorCommand
31+
let closeCommand: DoorCommand
3332

34-
init(deleteCommand: FileDeleteCommand, moveCommand: FileMoveCommand) {
35-
self.deleteCommand = deleteCommand
36-
self.moveCommand = moveCommand
33+
init(doors: String) {
34+
self.openCommand = OpenCommand(doors:doors)
35+
self.closeCommand = CloseCommand(doors:doors)
3736
}
3837

39-
func delete() {
40-
deleteCommand.execute()
38+
func close() -> String {
39+
return closeCommand.execute()
4140
}
4241

43-
func move() {
44-
moveCommand.execute()
42+
func open() -> String {
43+
return openCommand.execute()
4544
}
46-
}
45+
}
Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
1-
let deleteCommand = FileDeleteCommand(file: "/path/to/testfile")
2-
let moveCommand = FileMoveCommand(file: "/path/to/testfile")
3-
let fileManager = FileManager(deleteCommand:deleteCommand , moveCommand: moveCommand)
1+
let podBayDoors = "Pod Bay Doors"
2+
let doorModule = HAL9000DoorsOperations(doors:podBayDoors)
43

5-
fileManager.delete()
6-
fileManager.move()
4+
doorModule.open()
5+
doorModule.close()

0 commit comments

Comments
 (0)