Python
設計模式
中介者模式
設計模式
中介者模式
class ChatRoom:
def __init__(self):
self.UserList = []
def showMessage(self, User, Message):
pass
def Registor(self, User):
self.UserList.append(User)
def UnRegistor(self, User):
self.UserList.remove(User)
class CreateChatRoom(ChatRoom):
def showMessage(self, User, Message):
if User in self.UserList:
print(User.UserName,Message)
else:
print('User Not in System')
class User:
def __init__(self):
self.UserName = ''
self.Mediator = ChatRoom()
def SetChatRoom(self, chatRoom):
self.Mediator = chatRoom
def showMessage(self, user,Message):
self.Mediator.showMessage(user,Message)
class GM(User):
def __init__(self):
self.UserName = 'GM'
self.Mediator = None
class VIP(User):
def __init__(self):
self.UserName = 'VIP'
self.Mediator = None
class
Guest(User):
def __init__(self):
self.UserName = 'Guest'
self.Mediator = None
Chat = CreateChatRoom()
G = GM()
G.SetChatRoom(Chat)
V = VIP()
V.SetChatRoom(Chat)
Guest1 = Guest()
Guest1.SetChatRoom(Chat)
Chat.Registor(G)
Chat.Registor(V)
Chat.Registor(Guest1)
G.showMessage(G, 'I am GM')
V.showMessage(V, 'I am VIP')
Guest1.showMessage(Guest1, 'I am Guest1')
程式碼說明
定義中介者Chatroom,實作CreateChatRoom,透過中介者溝通物件,User,實作物件GM、VIP、Guest,以下為執行過程,需要注意的是真正的聊天室,是在不同執行緒以及不同台電腦上執行。
留言
張貼留言