全文:959字,預計閱讀時間:8分鐘
/** * 飲品. * * @author jialin.li * @date 2019-12-26 22:58 */ public interface Beverage { /** 獲取描述 */ String getDescription(); /** 獲取金額 */ double getPrice(); }
/** * 咖啡豆1 * * @author jialin.li * @date 2019-12-26 22:59 */ public class CoffeeBean1 implements Beverage { @Override public String getDescription() { return "第一種咖啡豆"; } @Override public double getPrice() { return 10d; } }
/** * 咖啡豆2 * * @author jialin.li * @date 2019-12-26 23:00 */ public class CoffeeBean2 implements Beverage{ @Override public String getDescription() { return "第一種咖啡豆"; } @Override public double getPrice() { return 12.5d; } }
/** * 裝飾器. * * @author jialin.li * @date 2019-12-26 23:02 */ public class Decorator implements Beverage{ protected Beverage coffee; @Override public String getDescription() { return "裝飾器,由子類重寫方法"; } @Override public double getPrice() { return 0; } }
/** * 蜂蜜. * * @author jialin.li * @date 2019-12-26 23:07 */ public class Honey extends Decorator { public Honey(Beverage coffee) { this.coffee = coffee; } @Override public String getDescription() { return coffee.getDescription() + "加蜂蜜"; } @Override public double getPrice() { return coffee.getPrice() + 4.5d; } }
/** * 牛奶. * * @author jialin.li * @date 2019-12-26 23:03 */ public class Milk extends Decorator { public Milk(Beverage coffee) { this.coffee = coffee; } @Override public String getDescription() { return coffee.getDescription() + "加牛奶"; } @Override public double getPrice() { return coffee.getPrice() + 1.5d; } }
/** * 摩卡. * * @author jialin.li * @date 2019-12-26 23:05 */ public class Mocha extends Decorator { public Mocha(Beverage coffee) { this.coffee = coffee; } @Override public String getDescription() { return coffee.getDescription() + "加摩卡"; } @Override public double getPrice() { return coffee.getPrice() + 2.5d; } }
/** * 測試類. * * @author jialin.li * @date 2019-12-26 23:09 */ public class Main { public static void main(String[] args) { CoffeeBean1 coffee1 = new CoffeeBean1(); CoffeeBean2 coffee2 = new CoffeeBean2(); // 加蜂蜜 Beverage honey = new Honey(coffee1); // 加摩卡 Beverage mocha = new Mocha(honey); System.out.println(mocha.getDescription()); System.out.println(mocha.getPrice()); // 加牛奶 Milk milk = new Milk(coffee2); System.out.println(milk.getDescription()); System.out.println(milk.getPrice()); } }