装饰器模式浅谈

327 阅读2分钟

「这是我参与2022首次更文挑战的第26天,活动详情查看:2022首次更文挑战」。

一、什么是装饰器模式

装饰器模式:允许向一个现有对象添加功能,同时又不改变其结构。常见的运用有servlet,java的io流等。例如io流,FileInputStream可以读取文件,然后可以用ObjectInputStream对其进行包装,使用流进行读取时,使用的就是ObjectInputStream的功能。比如原来的io流只能读取文件,使用其它流包装过后他就有了新的功能。装饰器模式没有改变原来的io流,扩展了它的功能。

二、装饰器模式的实现

下面我就用杯子与装饰杯子做一个例子,进行实现。杯子自身是一个抽象的概念,然后有一个具体的玻璃杯。然后是抽象的装饰器,我为这个杯子装饰上颜色,装饰上卡通贴纸。

public interface AbstractGlass {
    void show();
}

抽象构件,杯子

public class ConcreateGlass implements AbstractGlass{
    @Override
    public void show() {
        System.out.println("这是一个玻璃杯");
    }
}

具体构件,具体的杯子。

public abstract class GlassDecorator implements AbstractGlass{
    protected AbstractGlass decoratorGlass;

    public GlassDecorator(AbstractGlass decoratorGlass){
        this.decoratorGlass = decoratorGlass;
    }
    @Override
    public void show() {
        decoratorGlass.show();
    }
}

抽象装饰角色,其中有一个抽象杯子作为属性(这个属性就时需要装饰的杯子),同时实现了抽象杯子接口。实现此接口时,先调用了要装饰的杯子本身的方法,然后可以再此基础上做增强。

public class PinkGlassDecorator extends GlassDecorator{
    public PinkGlassDecorator(AbstractGlass decoratorGlass) {
        super(decoratorGlass);
    }

    @Override
    public void show() {
        decoratorGlass.show();
        System.out.println("杯子加上了粉色");
    }
}

具体装饰角色,此处给杯子装饰上了粉色。

public class StickerGlassDecorator extends GlassDecorator{
    public StickerGlassDecorator(AbstractGlass decoratorGlass) {
        super(decoratorGlass);
    }

    @Override
    public void show() {
        decoratorGlass.show();
        System.out.println("杯子贴了卡通贴纸");
    }
}

具体装饰角色,给杯子贴上卡通贴纸。

public static void main(String[] args) {
    ConcreateGlass concreateGlass = new ConcreateGlass();
    concreateGlass.show();
    System.out.println("----");
    PinkGlassDecorator pinkGlassDecorator = new PinkGlassDecorator(concreateGlass);
    pinkGlassDecorator.show();
    System.out.println("----");
    StickerGlassDecorator stickerGlassDecorator = new StickerGlassDecorator(concreateGlass);
    stickerGlassDecorator.show();
    System.out.println("----");
    StickerGlassDecorator stickerAndPinkGlass = new StickerGlassDecorator(pinkGlassDecorator);
    stickerAndPinkGlass.show();
}

单独使用杯子,获得了原始的杯子。然后可以通过装饰角色,加上颜色和贴纸。

image.png

三、总结

装饰器模式的角色:

  1. component:抽象构件,component是我们的原始对象,上面的例子指的就是抽象的杯子。
  2. concreateComponent:具体构件或者基础构件,具体的杯子,最基础的杯子,可以被添加各种装饰,也可以单独使用。
  3. decorator:装饰角色,一般是一个抽象类,继承抽象构件,属性里面定义了一个component。比如上面的例子就定义了一个抽象的杯子。
  4. concreateDecorator:具体装饰角色。