Skip to content

Instantly share code, notes, and snippets.

@LH17
Created January 1, 2019 15:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LH17/31157d62cec4de8df410b903b79b72d6 to your computer and use it in GitHub Desktop.
Save LH17/31157d62cec4de8df410b903b79b72d6 to your computer and use it in GitHub Desktop.
Observer Design Pattern
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