设计模式——装饰器模式(Decorator Pattern)

定义:装饰器模式(Decorator Pattern)也叫包装模式(Wrapper Pattern),是指在不改变原有对象基础上,将功能附加到对象上,提供了比继承更有弹性的替代方案,可以扩展原有对象的功能。属于结构型模式。

生活中的装饰器模式:煎饼(可以加鸡蛋,可以加火腿,可以加肉),蛋糕(可以做奶油的,可以做水果的,还可以加巧克力,可以加好看的装饰品)

适用场景:用于扩展一个类的功能或给一个类添加附加职责,可以动态的给一个类添加功能,这些功能可以再动态撤销。

优点:

1)装饰器是对继承的有力补充,比继承更加灵活,并且大大降低耦合度,在不改变原有对象的i情况下,动态地给一个对象扩展功能;
2)可以使用不同装饰类,并且通过不同顺序的排列组合,可以实现不同的功能;
3)装饰器模式符合开闭原则;

缺点:

1)装饰类导致类增加,程序复杂度增加;
2)动态装饰时,多层嵌套装饰显得复杂;

框架:IO流,Cache

角色:抽象组件,具体组件,抽象的装饰器,具体的装饰器

结构图

设计模式——装饰器模式(Decorator Pattern)_第1张图片

案例代码

public abstract class Component {
    public abstract void operation();
}
public class ConcreteComponent extends Component  {
    @Override
    public void operation() {
        // TODO 具体组件对象实现细节
        System.out.println("具体实现组件A执行");
    }
}
public abstract class Decorator extends Component {
    // 抽象组件对象
    private Component component;

    /**
     * 构造方法传入继承的抽象组件对象
     * @param component
     */
    public Decorator(Component component) {
        this.component = component;
    }

    @Override
    public void operation() {
        // TODO 请求组件方法,在转发前可以添加附加功能
        System.out.println("抽象装饰器执行装饰");
        component.operation();
    }
}
public class ConcreteDecoratorA extends Decorator {
    public ConcreteDecoratorA(Component component) {
        super(component);
    }

    @Override
    public void operation() {
        // TODO 基于原有功能基础上可以添加附加功能
        System.out.println("具体实现装饰器A装饰");
        super.operation();
    }
}
public class ConcreteDecoratorB extends Decorator {
    public ConcreteDecoratorB(Component component) {
        super(component);
    }

    @Override
    public void operation() {
        // TODO 基于原有功能基础上可以添加附加功能
        System.out.println("具体实现装饰器B装饰");
        super.operation();
    }
}

源码中IO流运用装饰器模式

设计模式——装饰器模式(Decorator Pattern)_第2张图片

public class Test {
    public static void main(String[] args) throws Exception {
        InputStream is = new FileInputStream("PATH");
        BufferedInputStream bis = new BufferedInputStream(is); //装饰器模式
        bis.read();
        bis.close();
        OutputStream os = new FileOutputStream("");
        BufferedOutputStream bos = new BufferedOutputStream(os); //装饰器模式
        bos.write(1);
        BufferedReader br = new BufferedReader(new FileReader("path")); //装饰器模式
        String brStr = br.readLine();
        BufferedWriter bw = new BufferedWriter(new FileWriter(brStr)); //装饰器模式
        bw.newLine();
    }
}

你可能感兴趣的:(设计模式,设计模式,装饰器模式)