编程-设计模式 9:装饰器模式

设计模式 9:装饰器模式

定义与目的
  • 定义:装饰器模式允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装。
  • 目的:该模式的主要目的是在不改变现有对象的前提下,动态地给该对象添加额外的功能或职责。
实现示例

假设我们有一个文本处理系统,需要为文本添加不同的格式,如加粗、斜体等。我们可以使用装饰器模式来实现这个需求。

// 定义文本接口
interface TextComponent {
    String getText();
}

// 具体文本类 - 原始文本
class PlainText implements TextComponent {
    private String text;

    public PlainText(String text) {
        this.text = text;
    }

    @Override
    public String getText() {
        return text;
    }
}

// 装饰器基类
abstract class TextDecorator implements TextComponent {
    protected TextComponent component;

    public TextDecorator(TextComponent component) {
        this.component = component;
    }

    @Override
    public String getText() {
        return component.getText();
    }
}

// 具体装饰器 - 加粗
class BoldDecorator extends TextDecorator {
    public BoldDecorator(TextComponent component) {
        super(component);
    }

    @Override
    public String getText() {
        return "<b>" + component.getText() + "</b>";
    }
}

// 具体装饰器 - 斜体
class ItalicDecorator extends TextDecorator {
    public ItalicDecorator(TextComponent component) {
        super(component);
    }

    @Override
    public String getText() {
        return "<i>" + component.getText() + "</i>";
    }
}

// 客户端代码
public class Client {
    public static void main(String[] args) {
        TextComponent plainText = new PlainText("Hello, World!");
        TextComponent boldText = new BoldDecorator(plainText);
        TextComponent italicText = new ItalicDecorator(boldText);

        System.out.println(italicText.getText());  // 输出: <i><b>Hello, World!</b></i>
    }
}
使用场景
  • 当你需要在运行时动态地给对象添加额外的功能时。
  • 当你不想通过继承来扩展对象的功能时。
  • 当你希望以一种动态的方式添加职责,而不是通过生成子类来扩展功能时。

装饰器模式通过包装现有对象来动态地添加功能,而不改变其结构。这对于需要在不修改现有代码的基础上扩展功能的情况非常有用。

小结

装饰器模式是一种常用的结构型模式,它可以帮助你以一种动态的方式扩展对象的功能,而不需要通过生成子类来实现。这对于需要在运行时根据需求添加功能的场景非常有用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值