装饰模式以对客户端透明的方式扩展对象的功能,是继承关系的一个替代方案。就像是窗户一样,先是玻璃,玻璃装上框架,再涂上颜色,每进行一层,都会增加新一层赋予的新功能:
1 //抽象构件接口 2 interface Component{ 3 public void method(); 4 } 5 6 //具体构件类 7 class ConcreteComponent implements Component{ 8 9 @Override 10 public void method() { 11 //业务代码 12 } 13 14 } 15 16 //装饰者类 17 class Decorator implements Component{ 18 19 private Component component; 20 21 public Decorator(Component component){ 22 this.component = component; 23 } 24 25 @Override 26 public void method() { 27 component.method(); 28 } 29 30 } 31 32 //具体装饰者类 33 class DecoratorA extends Decorator{ 34 35 public DecoratorA(Component component){ 36 super(component); 37 } 38 39 public void method(){ 40 super.method(); 41 //其他业务代码 42 } 43 } 44 45 class DecoratorB extends Decorator{ 46 47 public DecoratorB(Component component){ 48 super(component); 49 } 50 51 public void method(){ 52 super.method(); 53 //其他业务代码 54 } 55 } 56 57 public class MyTest { 58 59 /** 60 * @param args 61 */ 62 public static void main(String[] args) { 63 Component part = new ConcreteComponent(); 64 Component part1 = new DecoratorA(part); 65 Component part2 = new DecoratorB(part1); 66 part2.method(); 67 } 68 69 }