【设计模式】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()
相关推荐
1024肥宅12 小时前
JavaScript常用设计模式完整指南
前端·javascript·设计模式
特立独行的猫a14 小时前
C++观察者模式设计及实现:玩转设计模式的发布-订阅机制
c++·观察者模式·设计模式
better_liang15 小时前
每日Java面试场景题知识点之-单例模式
java·单例模式·设计模式·面试·企业级开发
sg_knight15 小时前
什么是设计模式?为什么 Python 也需要设计模式
开发语言·python·设计模式
koping_wu15 小时前
【设计模式】设计模式原则、单例模式、工厂模式、模板模式、策略模式
单例模式·设计模式·策略模式
__万波__16 小时前
二十三种设计模式(九)--组合模式
java·设计模式·组合模式
__万波__17 小时前
二十三种设计模式(十)--外观模式
java·设计模式·外观模式
__万波__17 小时前
二十三种设计模式(十一)--享元模式
java·设计模式·享元模式
Henry Zhu12317 小时前
23种设计模式介绍以及C语言实现
c语言·开发语言·设计模式
ZouZou老师1 天前
C++设计模式之解释器模式:以家具生产为例
c++·设计模式·解释器模式