装饰器模式:给一个对象添加一些额外的操作,虽然此功能可以用继承实现,但装饰模式比生成子类更灵活。核心思想是动态组合,和aop很相似,关键步骤在于对装饰器类的继承。
package com.jerry.design.decorator;
// 测试类
public class Test {
public static void main(String[] args) {
Component component = new ConcreteComponent();
component.operation();
System.out.println("-------------");
component = new Decorator1(new ConcreteComponent());
component.operation();
}
}
interface Component {
void operation();
}
class ConcreteComponent implements Component {
public void operation() {
System.out.println("I'm in ConcreteComponent's operation");
}
}
class Decorator implements Component {
private Component component;
public Decorator(Component component) {
this.component = component;
}
public void operation() {
component.operation();
}
}
class Decorator1 extends Decorator {
public Decorator1(Component component) {
super(component);
}
public void operation() {
doSomething();
super.operation();
}
private void doSomething() {
System.out.println("doSomething: I'm in Decorator1's operation");
}
}