java設計模式精講 Debug 方式+記憶體分析 第11章 裝飾者模式
阿新 • • 發佈:2018-12-05
裝飾者模式
11-1 裝飾者模式講解
11-2 裝飾者模式coding
有一個煎餅類:
public class Battercake {
protected String getDesc() {
return "煎餅";
}
protected int cost( ) {
return 8;
}
}
煎餅加雞蛋類:
public class BattercakeWithEgg extends Battercake {
@Override
public String getDesc() {
return super.getDesc()+"加一個雞蛋";
}
@Override
public int cost() {
return super.cost()+1;
}
}
煎餅加雞蛋加香腸類:
public class BattercakeWithEggSausage extends BattercakeWithEgg{
@Override
public String getDesc() {
return super.getDesc()+"一個香腸";
}
@Override
public int cost() {
return super.cost()+2;
}
}
測試:
public class Test {
public static void main(String[]args){
Battercake battercake = new Battercake();
System.out.println(battercake.getDesc()+"銷售價格:"+battercake.cost());
BattercakeWithEgg battercakeWithEgg = new BattercakeWithEgg();
System.out.println(battercakeWithEgg.getDesc()+"銷售價格:"+battercakeWithEgg.cost());
BattercakeWithEggSausage battercakeWithEggSausage = new BattercakeWithEggSausage();
System.out.println(battercakeWithEggSausage.getDesc()+"銷售價格:"+battercakeWithEggSausage.cost());
}
}
執行結果:
煎餅銷售價格:8
煎餅加一個雞蛋銷售價格:9
煎餅加一個雞蛋一個香腸銷售價格:11
這個時候,有一個人加了兩個雞蛋,這個時候,根據上面的就是不能算出價格的;
現在,我們用裝飾者模式來寫:
有一個抽象的煎餅類:
public abstract class ABattercake {
protected abstract String getDesc();
protected abstract int cost();
}
煎餅類繼承於上面的抽象兼餅類:
public class Battercate extends ABattercake {
@Override
protected String getDesc() {
return "煎餅";
}
@Override
protected int cost() {
return 8;
}
}
我們讓抽象的裝飾者類繼承抽象的實體:
public class AbstractDecorator extends ABattercake{
private ABattercake aBattercake;
public AbstractDecorator(ABattercake aBattercake) {
this.aBattercake = aBattercake;
}
@Override
protected String getDesc() {
return aBattercake.getDesc();
}
@Override
protected int cost() {
return aBattercake.cost();
}
}
煎餅新增雞蛋的裝飾類繼承於抽象的裝飾類:
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;
}
}
煎餅新增香腸的裝飾類,繼承於抽象的裝飾類:
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;
}
}
這個就是現在的類圖:
測試:
public class Test {
public static void main(String[]args){
ABattercake aBattercake;
aBattercake = new Battercate();
aBattercake = new EggDecorator(aBattercake);
aBattercake = new EggDecorator(aBattercake);
aBattercake = new SausageDecorator(aBattercake);
System.out.println(aBattercake.getDesc()+"價格為:"+aBattercake.cost());
}
}
執行結果:
煎餅加一個雞蛋加一個雞蛋加一根香腸價格為:12