Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@tgnivekucn
Created March 5, 2023 08:16
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 tgnivekucn/053fb9a658de1815b4d6257b30955595 to your computer and use it in GitHub Desktop.
Save tgnivekucn/053fb9a658de1815b4d6257b30955595 to your computer and use it in GitHub Desktop.
ObserverPatternInSwift
class Subject {
var list: [Adventurer] = []
func add(adventurer: Adventurer) {
list.append(adventurer)
}
func remove(adventurer: Adventurer) {
if let index = list.firstIndex(where: { $0 == adventurer}) {
list.remove(at: index)
}
}
func sendQuestions(question: String) {}
}
class Association: Subject {
override func sendQuestions(question: String) {
print("send questions")
list.forEach { $0.getQuestions(question: question) }
}
}
class Adventurer: Hashable {
var id: String
var name: String
init(id: String, name: String) {
self.id = id
self.name = name
}
func hash(into hasher: inout Hasher) {
hasher.combine(id)
hasher.combine(name)
}
static func == (lhs: Adventurer, rhs: Adventurer) -> Bool {
return lhs.id == rhs.id
}
func getQuestions(question: String) {}
}
class Bard: Adventurer {
override func getQuestions(question: String) {
print("Bard get question")
}
}
class Gunman: Adventurer {
override func getQuestions(question: String) {
print("Gunman get question")
}
}
class Lancer: Adventurer {
override func getQuestions(question: String) {
print("Lancer get question")
}
}
let lancer = Lancer(id: UUID().uuidString, name: "lancer")
let bard = Bard(id: UUID().uuidString, name: "bard")
let gunman = Gunman(id: UUID().uuidString, name: "gunman")
let association = Association()
association.add(adventurer: lancer)
association.add(adventurer: bard)
association.add(adventurer: gunman)
association.sendQuestions(question: "ChatGPT can substitute the work of people :D")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment