A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 〃Mr.Zぐ 中级黑马   /  2013-5-31 18:54  /  1529 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

package decorator;
public class Demo {     
   
    public static void main(String[] args)
    {     
        Component component = new ConcreteComponent();     
        component.operation();     
        System.out.println("----------------------------------------");     
        component = new BeforeDecorator(new ConcreteComponent());     
        component.operation();  
      }
}
——————————————————————————————————
/**   
* 业务接口   
*/     
public interface Component {     
     
    void operation();     
}  
——————————————————————————————
/**   
* 具体业务类.   
*/     
public class ConcreteComponent implements Component {     
     
    public void operation() {     
        System.out.println("I'm "+this.getClass().getName());     
    }     
     
}  
——————————————————————————————————————
/**   
* 在业务执行前加点额外的操作.   
*/     
public class BeforeDecorator extends Decorator {     
     
    public BeforeDecorator(Component component) {     
        super(component);     
    }     
     
    public void operation() {     
        before();     
        super.operation();     
    }     
     
    private void before() {     
        System.out.println("before: I'm "+this.getClass().getName());     
    }     
     
}
以上代码补全
/**   
* 装饰类.   
*/     
public class Decorator implements Component {     
     
    private Component component;     
     
    public Decorator(Component component) {     
        this.component = component;     
    }     
     
    public void operation() {     
        component.operation();     
    }     
     
}   

BeforeDecorator 类的 super.operation();     
为什么会输出I'm decorator.ConcreteComponent

评分

参与人数 1技术分 +1 收起 理由
曹睿翔 + 1 很给力!

查看全部评分

2 个回复

倒序浏览
在装饰类中,
public Decorator(Component component) {     
      this.component = component;     
    }     
接收的是Component component创建的对象,也就是main方法里面的 、
Component component = new ConcreteComponent();
也就是接收的是ConcreteComponent对象
然后用 this.component,把ConcreteComponent给了 private Component component;中的component
当运行到这个方法的时候
public void operation() {     
        component.operation();     
    }     
相当于ConcreteComponent().operation(),也就是它自己调用了自己的operation()方法
所以输出的是类名和ConcreteComponent
I'm decorator.ConcreteComponent

看懂了吗?

评分

参与人数 1技术分 +1 收起 理由
曹睿翔 + 1 神马都是浮云

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马