设计模式-装饰者模式

本文介绍了装饰模式的概念和应用场景,通过汽车改装的例子展示了如何使用装饰模式在不修改原有对象的基础上增加功能。代码示例中,创建了比亚迪汽车类,并通过CarDecorator抽象类和CarTailDecorator、CarSkylightDecorator子类实现汽车添加尾翼和天窗的功能。装饰模式的优点在于其灵活性和符合开闭原则。在实际应用中,如Mybatis缓存实现就运用了装饰模式。
摘要由CSDN通过智能技术生成
装饰模式:

装饰模式(Decorator Pattern) :动态地给一个对象增加一些额外的职责(Responsibility),就增加对象功能来说,装饰模式比生成子类实现更为灵活。其别名也可以称为包装器(Wrapper、Decorator)。根据翻译的不同,装饰模式也有人称之为“油漆工模式”,它是一种对象结构型模式。

UML结构图如下:

在这里插入图片描述

Component 是抽象构件,定义一个对象接口,可以给这些对象动态的添加职责;
ConcreteComponent定义一个具体对象,实现 Component;

Decorator : 是装饰抽象类,实现接口, 作为所有装饰类的父类。
ConcreteDecorator: 是Decorator子类,具体装饰对象;

场景:

我们以汽车为例, 定义接口Car:【对应:Component 】

public interface Car {

    void operation();
}

新建汽车的实现类, 比亚迪: BYDCar 【对应:ConcreteComponent】:

public class BYDCar implements Car{

    @Override
    public void operation() {
        System.out.print("比亚迪-汉");
    }
}

现在汽车有了,我们要给汽车进行一下改装,而不改变原来的对象, 抽象类:CarDecorator 【对应:Decorator】

abstract class CarDecorator implements Car{

    Car component;

    public CarDecorator(Car component) {
        this.component = component;
    }
}

给原有汽车添加一个 尾翼 CarTailDecorator 【对应:ConcreteDecorator】:

public class CarTailDecorator extends CarDecorator{

    public CarTailDecorator(Car component) {
        super(component);
    }

    @Override
    public void operation() {
        System.out.print("加尾翼(");
        component.operation();
        System.out.print(")");
    }
}

给原有汽车添加一个天窗 CarSkylightDecorator【对应:ConcreteDecorator】:

public class CarSkylightDecorator extends CarDecorator{

    public CarSkylightDecorator(Car component) {
        super(component);
    }

    @Override
    public void operation() {
        System.out.print("加天窗(");
        component.operation();
        System.out.print(")");
    }
}

那么, 现在把 尾翼、天窗装饰到 比亚迪上, 测试类如下 Test :

public class Test {

    public static void main(String[] args) {
        // 原对象
        Car car = new BYDCar();
        // 装饰
        car = new CarTailDecorator(new CarSkylightDecorator(car));
        car.operation();
    }
}

执行后打印如下:
在这里插入图片描述

装饰者有点:
  • 不改变原有对象的情况下给一个对象扩展功能
  • 使用不同的组合可以实现不同的效果
  • 符合开闭原则
装饰者模式在源码中的应用:

Mybatis 缓存实现:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值