【JAVA设计模式】10.装饰器模式

装饰器模式,就是在被装饰对象上添加一层装饰,使用户直接操作装饰类就可对被装饰对象进行操作。

问:使用装饰器模式和直接使用继承有什么区别

答:直接使用继承在被装饰对象较多时会导致子类骤增,装饰器模式可以理解为和桥接模式一样是为了解决子类过多问题的解决方案,二者差别在于桥接模式是单纯为了解决多个独立维度变化,而装饰器模式是为了在源操作上加新的操作。

JDK中io即是使用装饰器模式:

OutputStream out = new DataOutputStream( new FileOutputStream( "test.txt") )

UML图:

定义一个需要被装饰接口,所有具体被装饰类都需要实现该接口:

interface Component{
    void operation();
}

具体实现类(可以有多种):

class ConcreteComponent implements Component {
    @Override
    public void operation() {
        System.out.println("one function in ConcreteComponent");
    }
}

装饰器父类所有具体装饰器类都继承该类,实现了Component接口,重写被装饰类的方法:

class Decorator implements Component {
    private Component component;

    public Decorator(Component component) {
        this.component = component;
    }

    @Override
    public void operation() {
        component.operation();
    }
}

继承装饰器类的具体装饰类,具体实现了原有基础上新增的方法:

class ConcreteDecorator extends Decorator {
    public ConcreteDecorator(Component component) {
        super(component);
    }

    public void anotherOperation() {
        System.out.println("another operation");
    }

    @Override
    public void operation() {
        super.operation();
        anotherOperation();
    }
}

客户端中的使用方法类似桥接模式:

ConcreteDecorator cd = new ConcreteDecorator(new ConcreteComponent());
cd.operation();
ConcreteDecorator cd1 = new ConcreteDecorator(new ConcreteComponent1());
cd1.operation();

JAVA代码:https://github.com/zhuaizhuaixi/design-pattern/tree/master/src/designpattern/structural/decorator

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值