Python 实现命令模式、中介者模式和解释器模式

2024年 6月 5日 34.2k 0

今天介绍三种行为型设计模式:命令模式、中介者模式和解释器模式。

Python 实现命令模式、中介者模式和解释器模式-1

1.命令模式

它将请求封装成一个对象,从而使得可以用不同的请求对客户进行参数化。命令模式也支持撤销操作。

(1) 命令模式的结构

命令模式的核心是命令对象和接收者对象之间的关系。命令对象封装了一个特定的请求,包含了执行该请求的方法。接收者对象负责实际执行请求。

以下是命令模式的基本结构:

# 命令对象接口
class Command:
    def execute(self):
        pass

    def undo(self):
        pass

# 具体命令对象类
class ConcreteCommandA(Command):
    def __init__(self, receiver):
        self.receiver = receiver

    def execute(self):
        self.receiver.action_a()

    def undo(self):
        self.receiver.undo_action_a()

class ConcreteCommandB(Command):
    def __init__(self, receiver):
        self.receiver = receiver

    def execute(self):
        self.receiver.action_b()

    def undo(self):
        self.receiver.undo_action_b()

# 接收者对象类
class Receiver:
    def action_a(self):
        print("接收者执行动作A")

    def action_b(self):
        print("接收者执行动作B")

    def undo_action_a(self):
        print("接收者撤销动作A")

    def undo_action_b(self):
        print("接收者撤销动作B")

# 客户端代码
if __name__ == "__main__":
    receiver = Receiver()
    command_a = ConcreteCommandA(receiver)
    command_b = ConcreteCommandB(receiver)

    invoker = Invoker()
    invoker.set_command(command_a)
    invoker.execute_command()

    invoker.set_command(command_b)
    invoker.execute_command()

(2) 命令模式的应用场景

命令模式适用于以下场景:

  • 需要将请求的发送者和接收者解耦,使得它们可以独立地变化。
  • 需要支持撤销操作。

(3) 命令模式的优点

  • 命令模式将请求的发送者和接收者解耦,使得它们可以独立地变化。
  • 命令模式支持撤销操作。
  • 命令模式遵循开闭原则,新的命令对象可以很容易地添加到系统中,而不会影响到原有的代码。

(4) 命令模式的缺点

  • 命令模式中,命令对象和接收者对象之间存在循环依赖的关系,可能会导致循环引用的问题。

2.中介者模式

它通过封装一系列对象之间的交互,将对象之间的耦合度降低到最低。中介者模式将对象之间的交互转移给中介者对象,从而使得对象之间不再直接相互引用。

(1) 中介者模式的结构

中介者模式的核心是中介者对象,它封装了一系列对象之间的交互逻辑。中介者对象通常包含一个或多个接口,用于与其他对象进行通信。

以下是中介者模式的基本结构:

# 中介者接口
class Mediator:
    def send(self, message, colleague):
        pass

# 同事类接口
class Colleague:
    def set_mediator(self, mediator):
        pass

    def send(self, message):
        pass

    def receive(self, message):
        pass

# 具体中介者类
class ConcreteMediator(Mediator):
    def __init__(self):
        self.colleague_a = None
        self.colleague_b = None

    def set_colleague_a(self, colleague_a):
        self.colleague_a = colleague_a

    def set_colleague_b(self, colleague_b):
        self.colleague_b = colleague_b

    def send(self, message, colleague):
        if colleague == self.colleague_a:
            self.colleague_b.receive(message)
        elif colleague == self.colleague_b:
            self.colleague_a.receive(message)

# 具体同事类
class ConcreteColleagueA(Colleague):
    def __init__(self, mediator):
        self.mediator = mediator

    def set_mediator(self, mediator):
        self.mediator = mediator

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

    def receive(self, message):
        print("同事A收到消息:", message)

class ConcreteColleagueB(Colleague):
    def __init__(self, mediator):
        self.mediator = mediator

    def set_mediator(self, mediator):
        self.mediator = mediator

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

    def receive(self, message):
        print("同事B收到消息:", message)

# 客户端代码
if __name__ == "__main__":
    mediator = ConcreteMediator()

    colleague_a = ConcreteColleagueA(mediator)
    colleague_b = ConcreteColleagueB(mediator)

    mediator.set_colleague_a(colleague_a)
    mediator.set_colleague_b(colleague_b)

    colleague_a.send("Hello, colleague B!")
    colleague_b.send("Hi, colleague A!")

(2) 中介者模式的应用场景

中介者模式适用于以下场景:

  • 一组对象之间存在复杂的交互关系,导致对象之间的耦合度较高。
  • 要求对象之间的交互逻辑可以灵活地改变,而不需要修改对象之间的引用关系。

(3) 中介者模式的优点

  • 中介者模式将对象之间的交互逻辑封装到中介者对象中,从而使得对象之间的耦合度降低到最低。
  • 中介者模式使得对象之间的交互逻辑可以灵活地改变,而不需要修改对象之间的引用关系。
  • 中介者模式遵循开闭原则,新的同事类可以很容易地添加到系统中,而不会影响到原有的代码。

(4) 中介者模式的缺点

  • 中介者模式中,中介者对象通常需要知道所有的同事类,可能会导致中介者对象的职责过重。

3.解释器模式

它定义了一种语言的文法,并解析相应的语句。解释器模式通过定义语言的文法,将文法中的每个规则映射到一个类,然后通过递归的方式解析语句。

(1) 解释器模式的结构

解释器模式的核心是解释器类,它封装了解释语句的逻辑。解释器类通常包含一个或多个解释方法,用于解释语句的不同部分。

以下是解释器模式的基本结构:

# 抽象表达式类
class AbstractExpression:
    def interpret(self, context):
        pass

# 终结符表达式类
class TerminalExpression(AbstractExpression):
    def interpret(self, context):
        # 解释终结符表达式的逻辑
        pass

# 非终结符表达式类
class NonterminalExpression(AbstractExpression):
    def __init__(self):
        self.expressions = []

    def add_expression(self, expression):
        self.expressions.append(expression)

    def interpret(self, context):
        # 解释非终结符表达式的逻辑
        for expression in self.expressions:
            expression.interpret(context)

# 上下文类
class Context:
    def __init__(self):
        self.input = None
        self.output = None

# 客户端代码
if __name__ == "__main__":
    context = Context()

    # 构建语法树
    expression1 = TerminalExpression()
    expression2 = NonterminalExpression()
    expression3 = TerminalExpression()

    expression2.add_expression(expression1)
    expression2.add_expression(expression3)

    # 解释语句
    expression2.interpret(context)

(2) 解释器模式的应用场景

解释器模式适用于以下场景:

  • 一种语言的文法比较简单,且文法的规则可以通过类来表达。
  • 需要解析和执行一种特定的语言。

(3) 解释器模式的优点

  • 解释器模式将解释语句的逻辑封装到解释器类中,使得解释语句的逻辑可以灵活地改变。
  • 解释器模式遵循开闭原则,新的解释器类可以很容易地添加到系统中,而不会影响到原有的代码。

(4) 解释器模式的缺点

  • 解释器模式中,解释器类通常需要知道所有的语法规则,可能会导致解释器类的职责过重。

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论