一,定义与类型
在不改变原有对象的基础之上,将功能附加到对象上
提供了比继承更有弹性的替代方案
类型:结构型
二,适用场景
1.扩展一个类的功能或给一个类添加附加职责
2.动态的给一个对象添加功能,也可动态撤销
三,优点:
1.比继承灵活,不改变原有对象给一个对象扩展功能
2.通过使用不同装饰类以及这些装饰类的排列组合,实现不同效果
3.符合开闭原则
四,缺点:
出现更多的代码,更多的类,增加程序复杂性
动态装饰时,多层装饰会复杂
五,代码演练:
模拟场景:买煎饼加肠加蛋
在不使用装饰者模式
1.Battercake
public class Battercake {
protected String getDesc(){
return "煎饼";
}
protected int cost(){
return 8;
}
}
2.BattercakeWithEgg
public class BattercakeWithEgg extends Battercake {
@Override
public String getDesc() {
return super.getDesc()+"加一个鸡蛋";
}
@Override
public int cost() {
return super.cost()+1;
}
}
3.BattercakeWithEggSausage
public class BattercakeWithEggSausage extends BattercakeWithEgg{
@Override
public String getDesc() {
return super.getDesc()+"加一个香肠";
}
@Override
public int cost() {
return super.cost()+2;
}
}
4.Test
public class Test {
public static void main(String[] args) {
Battercake battercak=new Battercake();
System.out.println(battercak.getDesc()+" 销售价格:"+battercak.cost());
BattercakeWithEgg battercakeWithEgg=new BattercakeWithEgg();
System.out.println(battercakeWithEgg.getDesc()+" 销售价格:"+battercakeWithEgg.cost());
BattercakeWithEggSausage battercakeWithEggSausage=new BattercakeWithEggSausage();
System.out.println(battercakeWithEggSausage.getDesc()+" 销售价格:"+battercakeWithEggSausage.cost());
}
}
弊端:无法适应变化的需求
装饰者模式改进
1.ABattercake
public abstract class ABattercake {
protected abstract String getDesc();
protected abstract int cost();
}
2.Battercake
public class Battercake extends ABattercake {
@Override
protected String getDesc() {
return "煎饼";
}
@Override
protected int cost() {
return 8;
}
}
3.AbstractDecorator
public abstract class AbstractDecorator extends ABattercake {
private ABattercake aBattercake;
public AbstractDecorator(ABattercake aBattercake) {
this.aBattercake = aBattercake;
}
@Override
protected String getDesc() {
return this.aBattercake.getDesc();
}
@Override
protected int cost() {
return this.aBattercake.cost();
}
}
4.EggDecorator
public class EggDecorator extends AbstractDecorator{
public EggDecorator(ABattercake aBattercake) {
super(aBattercake);
}
@Override
protected String getDesc() {
return super.getDesc()+"加一个鸡蛋";
}
@Override
protected int cost() {
return super.cost()+1;
}
}
5.SausageDecorator
public class SausageDecorator extends AbstractDecorator {
public SausageDecorator(ABattercake aBattercake) {
super(aBattercake);
}
@Override
protected String getDesc() {
return super.getDesc()+"加一个香肠";
}
@Override
protected int cost() {
return super.cost()+2;
}
}
6.Test
public class Test {
public static void main(String[] args) {
ABattercake aBattercake;
aBattercake=new Battercake();
aBattercake=new EggDecorator(aBattercake);
aBattercake=new EggDecorator(aBattercake);
aBattercake=new SausageDecorator(aBattercake);
System.out.println(aBattercake.getDesc()+" 销售价格"+aBattercake.cost());
}
}
六,源码:
io流:FileInputStream等等
Spring:TransactionAwareCacheDecorator
ServletRequest
Mybatis:Cache下decorators包