装饰模式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();
}
}
可以添加多个装饰类,层级嵌套,多层次装饰会提高系统复杂度
装饰模式可以替代继承,解决类膨胀问题