装饰器模式

本篇主要介绍常用的一个设计模式——装饰器模式。

简介

装饰器模式:动态的将责任加到对象上,能扩展对象的功能,且比使用继承来达到扩展对象的功能更有弹性。

应用场合:设计的类数量过多、设计死板且父类加入的功能子类不能全部适用。JAVA中的IO就大量用到了此模式。

UML图

Component表示抽象的父类,ConcreteComponent表示具体的子类,Decorator表示装饰器,用来装饰ConcreteComponent,Decorator可以是抽象的,它持有指向Component的引用。ConcreteDecorator表示被装饰后的对象。下面我将用代码例子来实现图中的关系。

实例代码

Component.java

public interface Component {

    void run();
}

ConcreteComponent.java—— 实现了Component

public class ConcreteComponent implements Component {

    @Override
    public void run() {
        System.out.println("运行ConcreteComponent的run()方法");
    }

}

Decorator.java ——这里的装饰器并没使用抽象接口,而是使用了具体的装饰器。

public class Decorator implements Component {

    private Component component;
    //使用构造函数,获得component的引用
    public Decorator(Component component) {
        this.component = component;
    }

    @Override
    public void run() {
        System.out.println("装饰前的方法");
        component.run();
        System.out.println("装饰后的方法");
    }

}

AnotherDecorator.java ——另外一个装饰器。

public class AnotherDecorator implements Component {

    private Component component;
    //持有component引用
    public AnotherDecorator(Component component) {
        this.component = component;
    }

    @Override
    public void run() {
        System.out.println("另一个装饰前的方法");
        component.run();
        System.out.println("另一个装饰后的方法");
    }

}

测试代码DecoratorTest.java

public class DecoratorTest {

    public static void main(String[] args) {
        Component component = new ConcreteComponent();
        //使用Decorator包装ConcreteComponent
        component = new Decorator(component);
        //使用AnotherDecorator包装Decorator
        component = new AnotherDecorator(component);
        //执行使用AnotherDecorator包装后的run()方法。
        component.run();
    }

}

//控制台输出如下:
/*
另一个装饰前的方法
装饰前的方法
运行ConcreteComponent的run()方法
装饰后的方法
另一个装饰后的方法
*/

java中的IO类库就大量用到了装饰器模式。

//这里使用BufferedInputStream包装了FileInputStream,使得输入流有了缓冲的特性
InputStream in = new BufferedInputStream(new FileInputStream("file.txt"));
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值