java 中装饰器【io】的理解

谢谢博主:http://chenhua-1984.iteye.com/blog/565629的分享
这里记下代码,方便以后学习

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

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

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

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

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

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

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

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

以下是代码片度

Soucable.java

package decorator;

public interface Soucable {

    public void operation();
}
package decorator;

public class Source implements Soucable {

    public void operation(){
        System.out.println("这是原始的操作方法");
    }

}
package decorator;

public class Decorator1 implements Soucable {

    private Soucable souc = null;
    public Decorator1(Soucable souc){
        super();
        this.souc = souc;
    }
    public void operation() {
        System.out.println("第一个装饰器的前面");
        souc.operation();
        System.out.println("第一个装饰器的后面");
    }
}
package decorator;

public class Decorator2 implements Soucable{

    private Soucable souc = null;
    public Decorator2(Soucable souc){
        super();
        this.souc = souc;
    }
    public void operation() {
        System.out.println("第二个装饰器的前面");
        souc.operation();
        System.out.println("第二个装饰器的后面");
    }
}
package decorator;

public class Decorator3 implements Soucable{

    private Soucable souc = null;
    public Decorator3(Soucable souc){
        super();
        this.souc = souc;
    }
    public void operation() {
        System.out.println("第三个装饰器的前面");
        souc.operation();
        System.out.println("第三个装饰器的后面");
    }
}
package decorator;

public class Test {

    public static void main(String[] args) {
        Soucable souc = new Decorator1(new Decorator2(new Decorator3(new Source())));
        souc.operation();
    }
}

结果:

第一个装饰器的前面
第二个装饰器的前面
第三个装饰器的前面
这是原始的操作方法
第三个装饰器的后面
第二个装饰器的后面
第一个装饰器的后面
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值