装饰者模式
装饰者模式(Decorator Pattern)是指在不改变原有对象的基础之上,将功能附加到对象上,提供了比继承更有弹性的替代方案(扩展原有对象的功能),属于结构型模式。
代码
上班要迟到了,正好遇到一个煎饼摊想买一个填填肚子。煎饼基础版要5块钱,加一个鸡蛋1块,一根火腿2块,总价是多少? 在这里不知道我能吃几个鸡蛋和火腿的情况下,应该怎样去实现?
- UML类图
-
煎饼顶层抽象
Pancake
public abstract class Pancake { //套餐内容 protected abstract String getMsg(); //套餐价格 protected abstract double getPrice(); }
-
基础套餐实现类
BasePancake
public class BasePancake extends Pancake { @Override protected String getMsg() { return "一个煎饼"; } @Override protected double getPrice() { return 5; } }
-
装饰器类
public class PancakeDecorator extends Pancake { //持有基础类的引用 private Pancake pancake; public PancakeDecorator(Pancake pancake){ this.pancake = pancake; } @Override protected String getMsg() { return pancake.getMsg(); } @Override protected double getPrice() { return pancake.getPrice(); } }
-
加一个鸡蛋
public class PancakeWithEgg extends PancakeDecorator { public PancakeWithEgg(Pancake pancake) { super(pancake); } @Override protected String getMsg() { return super.getMsg()+"+1个鸡蛋,"; } @Override protected double getPrice() { return super.getPrice()+1; } }
-
加一根火腿
public class PancakeWithHum extends PancakeDecorator { public PancakeWithHum(Pancake pancake) { super(pancake); } @Override protected String getMsg() { return super.getMsg()+"+1根火腿,"; } @Override protected double getPrice() { return super.getPrice()+2; } }
-
测试类
public class PancakeDecoratorTest { public static void main(String[] args) { //先初始化基础套餐 Pancake pancake = new BasePancake(); pancake = new PancakeDecorator(pancake); System.out.println("我选择的套餐为:"+pancake.getMsg()+"\n 价格为:"+pancake.getPrice()); System.out.println("==================================="); //在基础套餐基础之上进行加餐 pancake = new PancakeWithEgg(pancake); pancake = new PancakeWithEgg(pancake); pancake = new PancakeWithHum(pancake); System.out.println("我选择的套餐为:"+pancake.getMsg()+"\n 价格为:"+pancake.getPrice()); } }
-
输出
我选择的套餐为:一个煎饼 价格为:5.0 =================================== 我选择的套餐为:一个煎饼+1个鸡蛋,+1个鸡蛋,+1根火腿, 价格为:9.0