GOF 装饰器模式

GOF 结构型模式 系列文章

  1. 适配器模式
  2. 装饰器模式
  3. 代理模式
  4. 桥接模式
  5. 组合模式
  6. 外观模式
  7. 享元模式


1. 概述

  • 功能作用

    • 动态的为一个对象增加新的功能
    • 装饰模式是一种用于代替继承的技术,无须通过继承增加子类就能扩展对象的新功能,可以动态的增加或删除对象的职责
    • 使用对象的关联关系代替继承关系,更加灵活,同时避免类型体系的快速膨胀,降低系统的耦合度。使得需要装饰的具体构建类和具体装饰类可以独立变化,以便增加新的具体构建类和具体装饰类。
  • 优点

    • 扩展对象功能,比继承灵活,不会导致类个数急剧增加
    • 可以对一个对象进行多次装饰,创造出不同行为的组合,得到功能更加强大的对象
    • 具体构建类和具体装饰类可以独立变化,用户可以根据需要自己增加
    • 新的具体构件子类和具体装饰子类。
  • 缺点

    • 产生很多小对象。大量小对象占据内存,一定程度上影响性能。
    • 装饰模式易于出错,调试排查比较麻烦。
  • 模式的结构

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

2. 实例

public class DecoratorTest {
    public static void main(String[] args) {
        Decorator2 decorator2 = new Decorator2(new Decorator1(new Car()));
        decorator2.operation();
    }
}

//抽象构件角色
interface ICar {
    public void operation();
}
//具体构件角色
class Car implements ICar {
    public Car() { System.out.println("new Car"); }
    public void operation() { System.out.println(this.getClass() + "::operation()"); }
}
//抽象装饰角色
class AbstractDecorator implements ICar {
    private ICar iCar;
    public AbstractDecorator(ICar iCar) { this.iCar = iCar; }
    public void operation() { iCar.operation(); }
}
//具体装饰角色1
class Decorator1 extends AbstractDecorator {
    public Decorator1(ICar iCar) { super(iCar); }
    public void operation() {
        super.operation();
        addedFunction();
    }
    public void addedFunction() { System.out.println(this.getClass() + "::addedFunction()");  }
}
//具体装饰角色2
class Decorator2 extends AbstractDecorator {
    public Decorator2(ICar iCar) { super(iCar); }
    public void operation() {
        super.operation();
        addedFunction();
    }
    public void addedFunction() { System.out.println(this.getClass() + "::addedFunction()");  }
}

测试结果如下
在这里插入图片描述


3. 装饰器模式的扩展

  • 如果只有一个具体构件而没有抽象构件时,可以让抽象装饰继承具体构件
  • 如果只有一个具体装饰时,可以将抽象装饰和具体装饰合并

参考链接

  1. 尚学堂_装饰器模式
  2. C语言中文网_装饰器模式
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值