You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在装饰器模式下从P类实例调用decoratorP的b()方法?

解决方案:基于组合的装饰器模式调整

首先明确:标准装饰器模式更推荐组合而非继承实现(你的场景用继承会导致被装饰类无法感知装饰器存在),通过让装饰器持有被装饰对象的引用,同时让被装饰对象反向持有装饰器的引用,就能实现P.a()执行完后调用decoratorP.b()的需求,具体步骤如下:


1. 定义统一抽象组件(接口)

先创建一个抽象基类,让P和decoratorP都实现这个接口,确保二者方法签名一致:

# component.py
from abc import ABC, abstractmethod

class Component(ABC):
    @abstractmethod
    def a(self):
        pass
    
    @abstractmethod
    def b(self):
        pass

2. 实现被装饰类P

给P类添加装饰器引用属性和设置方法,在a()执行完毕后调用装饰器的b():

# p.py
from component import Component

class P(Component):
    def __init__(self):
        self._decorator = None  # 存储装饰器实例
    
    def set_decorator(self, decorator):
        self._decorator = decorator
    
    def a(self):
        # P.a()的核心业务逻辑
        print("P.a() 核心逻辑执行")
        # 执行完后调用装饰器的b()
        if self._decorator:
            self._decorator.b()
    
    def b(self):
        print("P.b() 核心逻辑执行")

3. 实现装饰器类decoratorP

装饰器不再继承P,而是实现Component接口,持有被装饰对象的引用,初始化时将自身绑定给被装饰对象:

# decorator_p.py
from component import Component

class decoratorP(Component):
    def __init__(self, component: Component):
        self._component = component
        # 将当前装饰器实例绑定给被装饰对象
        self._component.set_decorator(self)
    
    def a(self):
        # 装饰器的额外操作
        print("decoratorP.a() 额外操作执行")
        # 调用被装饰对象的a()
        self._component.a()
    
    def b(self):
        # 装饰器的额外操作
        print("decoratorP.b() 额外操作执行")
        # 调用被装饰对象的b()
        self._component.b()

4. 主程序调用验证

# main.py
from p import P
from decorator_p import decoratorP

# 创建被装饰对象
p_obj = P()
# 用装饰器包装
decorator_obj = decoratorP(p_obj)
# 调用装饰器的a()
decorator_obj.a()

执行结果:

decoratorP.a() 额外操作执行
P.a() 核心逻辑执行
decoratorP.b() 额外操作执行
P.b() 核心逻辑执行

关键逻辑说明

  • 装饰器通过组合持有被装饰对象,符合装饰器模式的开闭原则(可动态添加/移除装饰器,无需修改原有类代码)
  • 被装饰对象P通过set_decorator方法持有装饰器引用,从而在自身a()执行完后能回调装饰器的b()
  • 所有逻辑封装在装饰器和被装饰类内部,完全不需要主程序做额外干预

内容的提问来源于stack exchange,提问作者DoZmeR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 08:05:34