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 说]: 你好,见到你真高兴.
标签:__,name,Mediator,Python,Pattern,self,user,msg,def From: https://www.cnblogs.com/geovindu/p/16820270.html