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 |