门面模式 与 装饰器模式(2)

简介: 门面模式 与 装饰器模式(2)

六、装饰器模式代码示例


image.png


来看一个这样的场景,上班族白领其实大多有睡懒觉的习惯,每天早上上班都是踩点,于是很多小伙伴为了多赖一会儿床都不吃早餐。那么,也有些小伙伴可能在上班路上碰到卖煎饼的路边摊,都会顺带一个到公司茶水间吃早餐。卖煎饼的大姐可以给你的煎饼加鸡蛋,也可以加香肠。


首先创建一个煎饼Battercake类:


public class Battercake {
    protected String getMsg(){ return "煎饼";}
    public int getPrice(){ return 5;}
}


创建一个加鸡蛋的煎饼BattercakeWithEgg类:


public class BattercakeWithEgg extends Battercake {
    @Override 
    protected String getMsg(){ return super.getMsg() + "+1个鸡蛋";}
    @Override 
    //加一个鸡蛋加 1 块钱 
    public int getPrice(){ return super.getPrice() + 1;}
}


再创建一个既加鸡蛋又加香肠的BattercakeWithEggAndSausage类:


public class BattercakeWithEggAndSauage extends BattercakeWithEgg {
    @Override
    protected String getMsg(){ return super.getMsg() + "+1根香肠";}
    @Override
    //加一个香肠加 2 块钱
    public int getPrice(){ return super.getPrice() + 2;}
}


编写客户端测试代码:


public class Test {
    public static void main(String[] args) {
        Battercake battercake = new Battercake();
        System.out.println(battercake.getMsg() + ",总价:" + battercake.getPrice());
        BattercakeWithEgg battercakeWithEgg = new BattercakeWithEgg();
        System.out.println(battercakeWithEgg.getMsg() + ",总价:" + battercakeWithEgg.getPrice());
        BattercakeWithEggAndSauage battercakeWithEggAndSauage = new BattercakeWithEggAndSauage();
        System.out.println(battercakeWithEggAndSauage.getMsg() + ",总价:" + battercakeWithEggAndSauage.getPrice());
    }


运行结果:


煎饼,总价:5
煎饼+1个鸡蛋,总价:6
煎饼+1个鸡蛋+1根香肠,总价:8


运行结果没有问题。


但是,如果用户需要一个加2个鸡蛋加1根香肠的煎饼,那么用我们现在的类

结构是创建不出来的,也无法自动计算出价格,除非再创建一个类做定制。如果需求再变,一直加定制

显然是不科学的。那么下面我们就用装饰器模式来解决上面的问题。


首先创建一个建煎饼的抽象

Battercake类:


public abstract class Battercake {
    protected abstract String getMsg();
    protected abstract int getPrice();
}
目录
相关文章
|
4月前
结构型 装饰器模式
结构型 装饰器模式
16 0
|
10天前
|
设计模式
装饰器模式
装饰器模式
9 0
|
1月前
|
设计模式 C++
【C++】—— 装饰器模式
【C++】—— 装饰器模式
|
4月前
|
前端开发
结构型 外观模式
结构型 外观模式
16 0
|
8月前
|
设计模式
2023-6-26-第八式装饰器模式
2023-6-26-第八式装饰器模式
59 0
|
9月前
装饰模式
装饰模式
40 0
|
9月前
打扮一下(装饰模式)
打扮一下(装饰模式)
42 0
装饰模式——添衣加被
装饰模式——添衣加被
|
10月前
|
前端开发 BI
关于装饰器模式我所知道的
关于装饰器模式我所知道的
50 0
|
10月前
|
设计模式
我认为的装饰器模式
我认为的装饰器模式
72 0