设计模式--装饰模式

Decorator定义:
动态给一个对象添加一些额外的职责,就象在墙上刷油漆.使用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");
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值