动态给一个对象添加一些额外的职责,就象在墙上刷油漆.使用Decorator模式相比用生成子类方式达到功能的扩充显得更为灵活.
为什么使用Decorator?
我们通常可以使用继承来实现功能的拓展,如果这些需要拓展的功能的种类很繁多,那么势必生成很多子类,增加系统的复杂性,同时,使用继承实现功能拓展,我们必须可预见这些拓展功能,这些功能是编译时就确定了,是静态的.
使用Decorator的理由是:这些功能需要由用户动态决定加入的方式和时机.Decorator提供了"即插即用"的方法,在运行期间决定何时增加何种功能.
package Decorator; public abstract class SchoolReport { public abstract void report(); public abstract void sign(String name); }
package Decorator; public abstract class Decorator extends SchoolReport { private SchoolReport report; public Decorator(SchoolReport report) { super(); this.report = report; } public void report() { this.report.report(); } public void sign(String name) { this.report.sign(name); } }
package Decorator; public class FouthGradeSchoolReport extends SchoolReport { @Override public void report() { System.out.println("ok"); } @Override public void sign(String name) { System.out.println(name + "--"); } }
package Decorator; public class HighSchoolDecorator extends Decorator { public HighSchoolDecorator(SchoolReport report) { super(report); } private void reportHighScore() { System.out.println("装饰后的"); } @Override public void report() { this.reportHighScore(); super.report(); } }
package Decorator; public class SortDecorator extends Decorator { public SortDecorator(SchoolReport report) { super(report); } private void peportSort() { System.out.println("装饰排名"); } @Override public void report() { super.report(); this.peportSort(); } }
package Decorator; public class Client { public static void main(String[] args) { SchoolReport report; report=new FouthGradeSchoolReport(); report=new HighSchoolDecorator(report); report=new SortDecorator(report); report.report(); report.sign("pass"); } }