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 说]: 你好,见到你真高兴.程序员节节日快乐

 

 

posted @ 2022-10-24 06:42  ®Geovin Du Dream Park™  阅读(19)  评论(0编辑  收藏  举报