设计模式之装饰模式

动态的给一个对象添加一些额外的职责,同时又不改变其原本的结构,作为原有类的包装,就增加功能来说,装饰模式比生成子类更为灵活。

原本对象:

/**
 * 原本功能
 */
interface Component {

    /**
     * 原本功能
     */
    void operation();

}

@Log4j2
class ConcreteComponent implements Component {

    @Override
    public void operation() {
        log.info("具体功能的操作");
    }
}

装饰对象:

@Data
abstract class AbstractDecorator implements Component {

    private Component component;

    @Override
    public void operation() {
        Optional.ofNullable(component).ifPresent(Component::operation);
    }
}

@Log4j2
class ConcreteComponentDecorator extends AbstractDecorator {

    @Override
    public void operation() {
        super.operation();
        decorate();
    }

    private void decorate() {
        log.info("装饰原本功能");
    }
}

访问装饰对象:

        Component component = new ConcreteComponent();
        log.info("装饰前");
        component.operation();
        ConcreteComponentDecorator decorator = new ConcreteComponentDecorator();
        decorator.setComponent(component);
        log.info("装饰后");
        decorator.operation();

结果:

16:12:08.267 [main] INFO com.learn.putc.designpatterns.structure.decorate.DecoratePattern - 装饰前
16:12:08.276 [main] INFO com.learn.putc.designpatterns.structure.decorate.ConcreteComponent - 具体功能的操作
16:12:08.281 [main] INFO com.learn.putc.designpatterns.structure.decorate.DecoratePattern - 装饰后
16:12:08.373 [main] INFO com.learn.putc.designpatterns.structure.decorate.ConcreteComponent - 具体功能的操作
16:12:08.373 [main] INFO com.learn.putc.designpatterns.structure.decorate.ConcreteComponentDecorator - 装饰原本功能

如果你不想在增加很多子类的情况下扩展功能,就可以考虑装饰模式,如果是多层继承用装饰模式来替代还是比较复杂,所以适合的场景才是用设计模式的前提。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值