DuMediator.py
# 中介者模式 Mediator Pattern # ParticipantReference: import sys ''' class User(object): def __init__(self, med, name): self.mediator = med self.name = name #self.send=send() #self.receive=receive() @abstractmethod def send(self, msg): pass @abstractmethod def receive(self, msg): pass def __str__(self): return self.name # 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 userDu = DuMediator.User("GeovinDu") userDu2 = DuMediator.User("geovindu") userDu3 = DuMediator.User("涂聚文") userDu4 = DuMediator.User("geovin") userDu.sendMessage("你好,见到你真高兴.") userDu2.sendMessage("你好,见到你真高兴.") userDu3.sendMessage("你好,见到你真高兴.") userDu4.sendMessage("你好,见到你真高兴.") print("\n")
输出:
[GeovinDu 说]: 你好,见到你真高兴. [geovindu 说]: 你好,见到你真高兴. [涂聚文 说]: 你好,见到你真高兴. [geovin 说]: 你好,见到你真高兴.
原文地址:http://www.cnblogs.com/geovindu/p/16820270.html
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,请务用于商业用途!
3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需!
7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员!
8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载
声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性