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

装饰器模式是一种结构型设计模式,它允许在不修改原有对象的基础上动态添加功能。通过创建包装对象,装饰器模式可以扩展类的功能,提供比继承更灵活的扩展方式。在Java IO流和缓存等框架中广泛应用。生活中的例子如煎饼和蛋糕的配料,可以自由组合添加。装饰器模式的优点在于灵活性和可扩展性,但可能导致类的数量增加,增加复杂性。在选择使用时,应考虑其适用场景和优缺点。
摘要由CSDN通过智能技术生成

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

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

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

优点:

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

缺点:

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

框架:IO流,Cache

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

结构图

案例代码

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流运用装饰器模式

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();
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值