Python: Mediator Pattern
DuMediator.py
# 中介者模式 Mediator Pattern import sys # ParticipantReference: class User(object): def __init__(self, med, name): self.mediator = med self.name = name def send(self, msg): pass def receive(self, msg): pass # The Mediator: class ChatMediator(object): def __init__(self): self.users = [] def add_user(self, user): self.users.append(user) def send_message(self, msg, user): for u in self.users: if u != user: u.receive(msg) # Participant class ConcreteUser(User): def send(self, msg): print(self.name + ": 发送消息: " + msg) self.mediator.send_message(msg, self) def receive(self, msg): print(self.name + ": 收到的消息: " + msg) # geovindu: two class ChatRoom(object): '''Mediator class.''' def __init__(self): self.users = [] def add_user(self, user): self.users.append(user) def displayMessage(self, user, message): print("[{} 说]: {}".format(user, message)) class User(object): '''A class whose instances want to interact with each other.''' def __init__(self, name): self.name = name self.chatRoom = ChatRoom() def sendMessage(self, message): self.chatRoom.displayMessage(self, message) def __str__(self): return self.name
main.py 调用
# 中介者模式 Mediator Pattern mediator = DuMediator.ChatMediator() userDu = DuMediator.ConcreteUser(mediator,"GeovinDu") userDu2 = DuMediator.ConcreteUser(mediator,"geovindu") userDu3 = DuMediator.ConcreteUser(mediator,"涂聚文") userDu4 = DuMediator.ConcreteUser(mediator,"geovin") mediator.add_user(userDu) mediator.add_user(userDu2) mediator.add_user(userDu3) mediator.add_user(userDu4) userDu.send("Hello 2024 程序员节节日快乐.") print("\n") GeovinDu = DuMediator.User("GeovinDu") GeovinDu2 = DuMediator.User("geovindu") GeovinDu3 = DuMediator.User("涂聚文") GeovinDu4 = DuMediator.User("geovin") GeovinDu.sendMessage("你好,见到你真高兴.程序员节节日快乐") GeovinDu2.sendMessage("你好,见到你真高兴.程序员节节日快乐") GeovinDu3.sendMessage("你好,见到你真高兴.程序员节节日快乐") GeovinDu4.sendMessage("你好,见到你真高兴.程序员节节日快乐")
输出:
GeovinDu: 发送消息: Hello 2024 程序员节节日快乐. geovindu: 收到的消息: Hello 2024 程序员节节日快乐. 涂聚文: 收到的消息: Hello 2024 程序员节节日快乐. geovin: 收到的消息: Hello 2024 程序员节节日快乐. [GeovinDu 说]: 你好,见到你真高兴.程序员节节日快乐 [geovindu 说]: 你好,见到你真高兴.程序员节节日快乐 [涂聚文 说]: 你好,见到你真高兴.程序员节节日快乐 [geovin 说]: 你好,见到你真高兴.程序员节节日快乐
哲学管理(学)人生, 文学艺术生活, 自动(计算机学)物理(学)工作, 生物(学)化学逆境, 历史(学)测绘(学)时间, 经济(学)数学金钱(理财), 心理(学)医学情绪, 诗词美容情感, 美学建筑(学)家园, 解构建构(分析)整合学习, 智商情商(IQ、EQ)运筹(学)生存.---Geovin Du(涂聚文)