Java设计模式之装饰模式

本文深入探讨了装饰模式的原理与实现细节,通过具体的类图和代码示例,展示了如何使用装饰模式来扩展对象的功能,同时保持代码的灵活性与可维护性。重点讲解了装饰模式中的关键角色,包括抽象构件、具体构件、装饰和具体装饰角色,并通过接口、具体构件、装饰角色和具体装饰角色的实现,阐述了装饰模式的基本流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

装饰模式的类图如下:

菱形表示关联关系,可以理解为车轮与汽车的关联关系

在装饰模式中的角色有:


  ●  抽象构件(Component)角色:给出一个抽象接口,以规范准备接收附加责任的对象。


  ●  具体构件(ConcreteComponent)角色:定义一个将要接收附加责任的类。


  ●  装饰(Decorator)角色:持有一个构件(Component)对象的实例,并定义一个与抽象构件接口一致的接口。


  ●  具体装饰(ConcreteDecorator)角色:负责给构件对象“贴上”附加的责任。

接口:

public interface Component {
    
    public void sampleOperation();
    
}
具体构件:

public class ConcreteComponent implements Component {

    @Override
    public void sampleOperation() {
        // 写相关的业务代码
    }

}
装饰角色:

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

    @Override
    public void sampleOperation() {
        // 委派给构件
        component.sampleOperation();
    }
    
}
具体装饰角色:

public class ConcreteDecoratorA extends Decorator {

    public ConcreteDecoratorA(Component component) {
        super(component);
    }
    
    @Override
    public void sampleOperation() {
     super.sampleOperation();
        // 写相关的业务代码
    }
}
public class ConcreteDecoratorB extends Decorator {

    public ConcreteDecoratorB(Component component) {
        super(component);
    }
    
    @Override
    public void sampleOperation() {
      super.sampleOperation();
        // 写相关的业务代码
    }
}
大致流程类似于流的封装:

<pre name="code" class="java" style="line-height: 27.999998092651367px;">1.<span style="white-space:pre">	</span>InputStream ins = new FileInputStream();
<span style="white-space:pre">	</span>DataInputStream dis = new DataInputStream(ins);
		
2.	ByteArrayInputStream bai = new ByteArrayInputStream();
	<span style="font-family: 'ms shell dlg'; font-size: 12px;">DataInputStream </span><span style="font-size: 12px; font-family: 'ms shell dlg';">dis = new DataInputStream(bai);</span>
	










评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值