装饰器模式可以用于增强一个现有的对象,同时又不改变其结构。
uml图如下:
代码如下:
抽象构件
1 2 3 4 5 6 7 8
| package com.notejava.decorator;
public interface Component { void operation(); }
|
具体构件
1 2 3 4 5 6 7 8 9 10 11
| package com.notejava.decorator;
public class ConcreteComponent implements Component { @Override public void operation() {
} }
|
装饰器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| package com.notejava.decorator;
public abstract class Decorator implements Component { protected Component component;
public Decorator(Component component) { this.component = component; }
@Override public abstract void operation(); }
|
具体装饰器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| package com.notejava.decorator;
public class ConcreteDecoratorA extends Decorator { public ConcreteDecoratorA(Component component) { super(component); }
@Override public void operation() { component.operation(); } }
|
具体装饰器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| package com.notejava.decorator;
public class ConcreteDecoratorB extends Decorator { public ConcreteDecoratorB(Component component) { super(component); }
@Override public void operation() { component.operation(); } }
|