Created
January 1, 2019 15:13
-
-
Save LH17/31157d62cec4de8df410b903b79b72d6 to your computer and use it in GitHub Desktop.
Observer Design Pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protocol Observable { | |
func add(customer: Observer) | |
func remove(customer : Observer) | |
func notify() | |
} | |
protocol Observer { | |
var id: Int { get set } | |
func update() | |
} | |
class AppleSeller: Observable { | |
private var observers: [Observer] = [] | |
private var count: Int = 0 | |
var appleCount: Int { | |
set { | |
count = newValue | |
notify() | |
} | |
get { | |
return count | |
} | |
} | |
func add(customer: Observer) { | |
observers.append(customer) | |
} | |
func remove(customer : Observer) { | |
observers = observers.filter{ $0.id != customer.id } | |
} | |
func notify() { | |
for observer in observers { | |
observer.update() | |
} | |
} | |
} | |
class Customer: Observer { | |
var id: Int | |
var observable: AppleSeller | |
var name: String | |
init(name: String, observable: AppleSeller, customerId: Int) { | |
self.name = name | |
self.observable = observable | |
self.id = customerId | |
self.observable.add(customer: self) | |
} | |
func update() { | |
print("Hurry \(name)! \(observable.appleCount) apples arrived at shop.") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment