裝飾模式Decorator Pattern
動態地給一個對象添加一些額外的職責,就增加功能而言,裝飾模式相對繼承更加靈活。
<span style="white-space:pre"> </span>//基本抽象類
public abstract class Component{
public abstract void action();
}
//具體工作類
public class ConcreteComponent extends Component{
@Override
public void action(){}//具體實現方法
}
//抽象裝飾類
public Decorator extends Component{
private Component component = null;
public Decorator(Component component){this.component=component;}
@Override
public void action(){
this.component.action();
}
}
//具體裝飾類
public ConcreteDecorator extends Component{
public ConcreteDecorator(Component component){super(component);}
private void method(){}//裝飾方法
public void action(){//重寫父類action方法
this.method();
super.action();
}
}
可以添加多個裝飾類,層級嵌套,多層次裝飾會提高系統複雜度裝飾模式可以替代繼承,解決類膨脹問題