设计模式之装饰器

Decorator装饰器,顾名思义,就是动态地给一个对象添加一些额外的职责,就好比为房子进行装修一样。因此,装饰器模式具有如下的特征:

它必须具有一个装饰的对象。

它必须拥有与被装饰对象相同的接口。

它可以给被装饰对象添加额外的功能。

用一句话总结就是:保持接口,增强性能。

装饰器通过包装一个装饰对象来扩展其功能,而又不改变其接口,这实际上是基于对象的适配器模式的一种变种。它与对象的适配器模式的异同点如下。

相同点:都拥有一个目标对象。

不同点:适配器模式需要实现另外一个接口,而装饰器模式必须实现该对象的接口。


实现代码:

package pattern.decorator;
 interface Sourcable {  
    public void operation();  
  
}  
class Source implements Sourcable {  
	  
    public void operation() {  
        System.out.println("原始类的方法");  
    }  
  
}  
class Decorator1 implements Sourcable {  
	  
    private Sourcable sourcable;  
    public Decorator1(Sourcable sourcable){  
        super();  
        this.sourcable=sourcable;  
    }  
      
    public void operation() {  
        System.out.println("第一个装饰器前");  
        sourcable.operation();  
        System.out.println("第一个装饰器后");  
  
    }  
  
}  
class Decorator2 implements Sourcable {  
	  
    private Sourcable sourcable;  
    public Decorator2(Sourcable sourcable){  
        super();  
        this.sourcable=sourcable;  
    }  
    public void operation() {  
        System.out.println("第二个装饰器前");  
        sourcable.operation();  
        System.out.println("第二个装饰器后");  
  
    }  
  
}  
class Decorator3 implements Sourcable {  
    
    private Sourcable sourcable;  
    public Decorator3(Sourcable sourcable){  
        super();  
        this.sourcable=sourcable;  
    }  
    public void operation() {  
        System.out.println("第三个装饰器前");  
        sourcable.operation();  
        System.out.println("第三个装饰器后");  
  
    }  
  
}  


public class DecoratorTest {  
	  
    /** 
     * @param args 
     */  
    public static void main(String[] args) {  
        Sourcable source = new Source();  
  
        // 装饰类对象   
        Sourcable obj = new Decorator1(new Decorator2(new Decorator3(source)));  
        obj.operation();  
    }  
  
}  

测试结果:


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值