装饰器模式:动态增强的艺术大师
装饰器模式是一种结构型设计模式,允许在不修改现有对象结构的情况下动态地扩展功能。通过将对象包装在装饰器类中,可以在运行时添加新的行为。这种模式的核心思想是组合优于继承,提供了更灵活的替代方案。
装饰器模式的核心概念
装饰器模式通过一个抽象组件类定义核心功能,具体组件类实现这些功能。装饰器类继承自抽象组件类,并包含一个指向组件对象的引用。装饰器类可以在调用组件对象的方法前后添加额外的行为。
抽象组件类通常是一个接口或抽象类,定义了基本操作。具体组件类实现了这些操作,而装饰器类则通过组合方式增强这些操作。这种结构允许无限嵌套装饰器,实现多层次的功能增强。
装饰器模式的实现示例
以下是一个Python实现的装饰器模式示例,展示如何动态地为文本处理功能添加装饰:
from abc import ABC, abstractmethod
class TextComponent(ABC):
@abstractmethod
def render(self) -> str:
pass
class PlainText(TextComponent):
def __init__(self, text: str):
self._text = text
def render(self) -> str:
return self._text
class TextDecorator(TextComponent):
def __init__(self, component: TextComponent):
self._component = component
@abstractmethod
def render(self) -> str:
pass
class BoldDecorator(TextDecorator):
def render(self) -> str:
return f"<b>{self._component.render()}</b>"
class ItalicDecorator(TextDecorator):
def render(self) -> str:
return f"<i>{self._component.render()}</i>"
# 客户端代码
text = PlainText("Hello, Decorator Pattern!")
decorated_text = ItalicDecorator(BoldDecorator(text))
print(decorated_text.render()) # 输出: <i><b>Hello, Decorator Pattern!</b></i>
这个示例中,PlainText是具体组件,BoldDecorator和ItalicDecorator是具体装饰器。装饰器可以嵌套组合,动态地为
325

被折叠的 条评论
为什么被折叠?



