Python中的设计模式:观察者模式与中介者模式

落花无声 2020-05-06 ⋅ 20 阅读

在Python中,设计模式是一种重要的编程范式,可用于解决各种复杂的问题。观察者模式和中介者模式是其中两种常见的模式。本文将介绍这两种模式的概念以及在Python中如何实现它们。

观察者模式

观察者模式是一种行为型设计模式,其中一个对象(称为主题)维护其依赖对象列表(称为观察者),并在发生状态变化时通知观察者。这种模式的目标是降低主题和观察者之间的耦合度。

实现观察者模式

在Python中,我们可以使用内置的ObservableObserver类来实现观察者模式。首先,我们需要定义一个主题类:

class Subject:
    def __init__(self):
        self._observers = []

    def attach(self, observer):
        self._observers.append(observer)

    def detach(self, observer):
        self._observers.remove(observer)

    def notify(self, message):
        for observer in self._observers:
            observer.update(message)

然后,我们可以定义一个观察者类:

class Observer:
    def update(self, message):
        print("收到消息:", message)

最后,我们可以创建一个主题对象,并添加观察者:

subject = Subject()

observer1 = Observer()
observer2 = Observer()

subject.attach(observer1)
subject.attach(observer2)

subject.notify("新消息")

运行上述代码,将输出:

收到消息: 新消息
收到消息: 新消息

这是因为我们的两个观察者都成功收到了来自主题的通知。

中介者模式

中介者模式是一种行为型设计模式,它定义了一个中介者对象,该对象封装了对象之间的交互逻辑。中介者模式的目标是减少对象之间的直接依赖关系,从而提高系统的可维护性和灵活性。

实现中介者模式

在Python中,我们可以使用第三方库mediator来实现中介者模式。首先,我们需要安装该库:

pip install mediator

然后,我们可以定义一个中介者类:

from mediator import Mediator


class ChatMediator(Mediator):
    def send(self, sender, message):
        print(sender, "发送消息:", message)
        for participant in self.participants:
            if participant != sender:
                participant.receive(message)


class Participant:
    def __init__(self, mediator, name):
        self.mediator = mediator
        self.name = name

    def send(self, message):
        self.mediator.send(self, message)

    def receive(self, message):
        print(self.name, "收到消息:", message)

最后,我们可以创建中介者对象、参与者对象,并让它们相互通信:

mediator = ChatMediator()

participant1 = Participant(mediator, "Participant 1")
participant2 = Participant(mediator, "Participant 2")
participant3 = Participant(mediator, "Participant 3")

mediator.register(participant1)
mediator.register(participant2)
mediator.register(participant3)

participant1.send("Hello")
participant2.send("Hi")
participant3.send("How are you?")

运行上述代码,将输出:

Participant 1 发送消息: Hello
Participant 2 收到消息: Hello
Participant 3 收到消息: Hello
Participant 2 发送消息: Hi
Participant 1 收到消息: Hi
Participant 3 收到消息: Hi
Participant 3 发送消息: How are you?
Participant 1 收到消息: How are you?
Participant 2 收到消息: How are you?

这是因为中介者在收到消息后会将其广播给其他参与者。

结论

观察者模式和中介者模式是两种常见的设计模式,在Python中都有实现的方式。观察者模式通过使用主题和观察者的抽象,减少了对象间的耦合度。中介者模式通过引入一个中介者对象,将对象之间的交互逻辑集中在一起,提高了系统的可维护性和灵活性。

通过了解和应用这两种设计模式,我们可以更好地组织我们的代码,使其更加模块化和可扩展。在实际开发中,我们可以根据需求选择适合的设计模式来解决问题。


全部评论: 0

    我有话说: