【设计模式】01-装饰器模式Decorator

作用:在不修改对象外观和功能的情况下添加或者删除对象功能,即给一个对象动态附加职能

装饰器模式主要包含以下角色。

  1. 抽象构件(Component)角色:定义一个抽象接口以规范准备接收附加责任的对象。
  2. 具体构件(ConcreteComponent)角色:实现抽象构件,通过装饰角色为其添加一些职责。
  3. 抽象装饰(Decorator)角色:继承抽象构件,并包含具体构件的实例,可以通过其子类扩展具体构件的功能。
  4. 具体装饰(ConcreteDecorator)角色:实现抽象装饰的相关方法,并给具体构件对象添加附加的责任。

package decorator;
public class DecoratorPattern {
    public static void main(String[] args) {
        Component p = new ConcreteComponent();
        p.operation();
        System.out.println("---------------------------------");
        Component d = new ConcreteDecorator(p);
        d.operation();
    }
}
//抽象构件角色
interface Component {
    public void operation();
}
//具体构件角色
class ConcreteComponent implements Component {
    public ConcreteComponent() {
        System.out.println("创建具体构件角色");
    }
    public void operation() {
        System.out.println("调用具体构件角色的方法operation()");
    }
}
//抽象装饰角色
class Decorator implements Component {
    private Component component;
    public Decorator(Component component) {
        this.component = component;
    }
    public void operation() {
        component.operation();
    }
}
//具体装饰角色
class ConcreteDecorator extends Decorator {
    public ConcreteDecorator(Component component) {
        super(component);
    }
    public void operation() {
        super.operation();
        addedFunction();
    }
    public void addedFunction() {
        System.out.println("为具体构件角色增加额外的功能addedFunction()");
    }
}

运行结果

创建具体构件角色
调用具体构件角色的方法operation()
---------------------------------
调用具体构件角色的方法operation()
为具体构件角色增加额外的功能addedFunction()

相关推荐

  1. 设计模式--装饰模式Decorator Pattern)

    2024-02-22 09:42:05       21 阅读
  2. 设计模式装饰模式Decorator Pattern)

    2024-02-22 09:42:05       19 阅读
  3. 装饰模式Decorator

    2024-02-22 09:42:05       35 阅读
  4. 设计模式-装饰模式 Decorator

    2024-02-22 09:42:05       31 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-02-22 09:42:05       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-02-22 09:42:05       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-02-22 09:42:05       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-02-22 09:42:05       20 阅读

热门阅读

  1. k8s-权限管理

    2024-02-22 09:42:05       32 阅读
  2. CDC 整合方案:MySQL > Flink CDC > Kafka > Hudi

    2024-02-22 09:42:05       32 阅读
  3. 通过API接口实现自动化数据同步

    2024-02-22 09:42:05       36 阅读
  4. 数据分析Pandas专栏---第二章<Pandas四个关键词>

    2024-02-22 09:42:05       30 阅读
  5. 高效的嵌入式系统架构设计

    2024-02-22 09:42:05       36 阅读
  6. 每天一个数据分析题(一百六十六)

    2024-02-22 09:42:05       32 阅读
  7. 开源模型应用落地-业务优化篇(六)

    2024-02-22 09:42:05       29 阅读