哪種Design pattern(Creational/Structural/Behavioural):
Behavioural 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
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 😀") | |