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

设计模式 9:装饰器模式

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

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

java 复制代码
// 定义文本接口
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>
    }
}
使用场景
  • 当你需要在运行时动态地给对象添加额外的功能时。
  • 当你不想通过继承来扩展对象的功能时。
  • 当你希望以一种动态的方式添加职责,而不是通过生成子类来扩展功能时。

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

小结

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

相关推荐
FG.几秒前
Day22
java·面试
菜鸟的迷茫2 分钟前
Redis 缓存雪崩、穿透、击穿面试题深度解析与 Spring Boot 实战代码示例
java
珹洺13 分钟前
C++算法竞赛篇:DevC++ 如何进行debug调试
java·c++·算法
SHUIPING_YANG21 分钟前
根据用户id自动切换表查询
java·服务器·数据库
爱吃烤鸡翅的酸菜鱼33 分钟前
IDEA高效开发:Database Navigator插件安装与核心使用指南
java·开发语言·数据库·编辑器·intellij-idea·database
惊涛骇浪、39 分钟前
SpringMVC + Tomcat10
java·tomcat·springmvc
墨染点香1 小时前
LeetCode Hot100【6. Z 字形变换】
java·算法·leetcode
ldj20201 小时前
SpringBoot为什么使用new RuntimeException() 来获取调用栈?
java·spring boot·后端
超龄超能程序猿1 小时前
Spring 应用中 Swagger 2.0 迁移 OpenAPI 3.0 详解:配置、注解与实践
java·spring boot·后端·spring·spring cloud
风象南1 小时前
SpringBoot配置属性热更新的轻量级实现
java·spring boot·后端