日期:2014-05-20  浏览次数:20758 次

io中修饰模式
最近在看学习io方面的东西,接触到修饰模式,就上网查了一下资料,动手写了一个,对运行的结果不太理解,求各位指点。
//源接口
public interface Sourceable {

public void operation();

}
//接口实现类
public class Source implements Sourceable {

@Override
public void operation() {
// TODO Auto-generated method stub
System.out.println("原始类的方法");
}

}
//修饰模式一
public class Decorator1 implements Sourceable {

private Sourceable sourceable;
public Decorator1(Sourceable sourceable){
super();
this.sourceable = sourceable;
}

@Override
public void operation() {
// TODO Auto-generated method stub
System.out.println("第一个装饰器前");
sourceable.operation();
System.out.println("第一个装饰器后");
}

}
//修饰模式二
public class Decorator2 implements Sourceable {

private Sourceable sourceable;

public Decorator2(Sourceable sourceable){
super();
this.sourceable = sourceable;
}

@Override
public void operation() {
// TODO Auto-generated method stub
System.out.println("第二个装饰器前");
sourceable.operation();
System.out.println("第二个装饰器后");
}

}
//修饰模式三
public class Decorator3 implements Sourceable {

private Sourceable sourceable;

public Decorator3(Sourceable sourceable){
super();
this.sourceable = sourceable;
}

@Override
public void operation() {
// TODO Auto-generated method stub
System.out.println("第三个装饰器前");
sourceable.operation();
System.out.println("第三个装饰器后");
}

}
//测试
public class DecoratorTest {

public static void main(String[] args) {
Sourceable source = new Source();//接口回调
//装饰类对象
Sourceable obj = new Decorator3(new Decorator2(new Decorator1(source)));
obj.operation();

//new Decorator1(source); 通过new创建了Decorator1的实例对象,而Decorator1是接口Sourceable的实现类  
//new Decorator2(Decorator1对象)相当于创建了另一个接口回调
}

}

---------------------------------------------------
测试结果
第三个装饰器前
第二个装饰器前
第一个装饰器前
原始类的方法
第一个装饰器后
第二个装饰器后
第三个装饰器后

不太理解的地方?
Sourceable obj = new Decorator3(new Decorator2(new Decorator1(source)));
相当于最外面的Decorate3的对象回调给接口obj,那为什么输出结果中有
第二个装饰器前
第一个装饰器前
第一个装饰器后
第二个装饰器后
能从创建对象,和分配内存的角度解释下吗?



------解决方案--------------------
new Decorator3(new Decorator2(new Decorator1(source))); 这个没有什么玄机,就是Decorator3里的sourceable类型是Decorator2,Decorator2里的sourceable字段的类型又是Decorator1。按一般理解就行。

首先输出“第三个装饰器前”,然后sourceable的类型是Decorator2,调用它的operation方法,输出“第二个装饰器前”,接下来的sourceable是Decorator1类型的,调用它的operation方法,输出“第一个装饰器前”。对于“。。。之后”,同理。

你可以单步调试一下, 调用过程就清晰明了了。