定义
动态地给一个对象添加一些额外的职责。
优点缺点及使用场景
优点
- 装饰类和被装饰类独立发展,不相互耦合。
- 动态扩展一个实现类的功能。
缺点
- 越多层装饰越复杂。
使用场景
需要动态扩展一个类的功能。
示例代码
/*
* 抽象业务类
*/
public abstract class SchoolReport
{
public abstract void report();
public abstract void sign();
}
public abstract class Decorator extends SchoolReport
{
private SchoolReport report;
public Decorator(SchoolReport report)
{
this. report = report;
}
@Override
public void report()
{
this.report.report();
}
@Override
public void sign()
{
this.report.sign();
}
public static void main(String[] args){
SchoolReport sReport = new FouthGradeSchoolReport();
sReport = new HighScoreDecorator(sReport);
sReport = new SortDecorator(sReport);
sReport.report();
}
}
/*
* 装饰类
*/
public class HighScoreDecorator extends Decorator
{
public HighScoreDecorator(SchoolReport report)
{
super(report);
}
public void highSoreReport(){
System.out.println("修饰的报告 high...");
}
public void report(){
this.highSoreReport();
super.report();
}
}
抽象装饰类中代理了业务接口,原始类进行装饰时,装饰类就相当于代理了该原始类,这样在原功能的基础上再动态调用装饰类自己的功能以达到动态增加功能的目的。