from abc import ABC, abstractmethod
class Mediator(ABC):
@abstractmethod
def send_message(self, message, sender):
pass
class ChatMediator(Mediator):
def __init__(self):
self._users = []
def add_user(self, user):
self._users.append(user)
def send_message(self, message, sender):
for user in self._users:
# Отправляем сообщение всем пользователям, кроме отправителя
if user != sender:
user.receive(message)
class User:
def __init__(self, name, mediator):
self.name = name
self._mediator = mediator
self._mediator.add_user(self)
def send(self, message):
print(f"{self.name} sends: {message}")
self._mediator.send_message(message, self)
def receive(self, message):
print(f"{self.name} receives: {message}")
def main():
mediator = ChatMediator()
user1 = User("Alice", mediator)
user2 = User("Bob", mediator)
user3 = User("Charlie", mediator)
user1.send("Hello, everyone!")
user2.send("Hi, Alice!")
user3.send("Hey, folks!")
main()
Alice sends: Hello, everyone!
Bob receives: Hello, everyone!
Charlie receives: Hello, everyone!
Bob sends: Hi, Alice!
Alice receives: Hi, Alice!
Charlie receives: Hi, Alice!
Charlie sends: Hey, folks!
Alice receives: Hey, folks!
Bob receives: Hey, folks!