装饰器模式:动态地给一个对象添加一些额外地职责,就增加功能来说,装饰器比子类更加灵活

    优点:在原对象基础上额外增加功能,而不影响原对象

    实现:咖啡店里售卖咖啡,加糖和加奶都需要额外收费,有的可以选择加糖,有的客人选择加奶,有的客人则选择原味。其实不管是加糖还是加奶,都是在原咖啡地基础上增加额外属性。

    1、抽象产品

    1. /**
    2. * 抽象产品-咖啡
    3. */
    4. public abstract class Coffee {
    5. /**
    6. * 获取咖啡名称
    7. */
    8. public abstract String getName();
    9. /**
    10. * 获取咖啡价格
    11. */
    12. public abstract Double getPrice();
    13. }

    2、实际产品

    1. /**
    2. * 实际产品-蓝山咖啡
    3. */
    4. public class LanShanCoffee extends Coffee{
    5. /**
    6. * 获取咖啡名称
    7. */
    8. public String getName(){
    9. return "蓝山咖啡";
    10. }
    11. /**
    12. * 获取咖啡价格
    13. */
    14. public Double getPrice(){
    15. return 8.0;
    16. }
    17. }
    18. /**
    19. * 实际产品-猫屎咖啡
    20. */
    21. public class MaoShiCoffee extends Coffee{
    22. /**
    23. * 获取咖啡名称
    24. */
    25. public String getName(){
    26. return "猫屎咖啡";
    27. }
    28. /**
    29. * 获取咖啡价格
    30. */
    31. public Double getPrice(){
    32. return 9.2;
    33. }
    34. }

    3、抽象装饰器类

    1. /**
    2. * 装饰器类
    3. */
    4. public abstract class Decorator extends Coffee{
    5. Coffee coffee;
    6. /**
    7. * 设置装饰类
    8. */
    9. public Decorator(Coffee coffee){
    10. this.coffee = coffee;
    11. }
    12. /**
    13. * 获取咖啡名称
    14. */
    15. public abstract String getName();
    16. /**
    17. * 获取咖啡价格
    18. */
    19. public abstract Double getPrice();
    20. }

    4、装饰器类实现

    1. /**
    2. * 牛奶-装饰器
    3. */
    4. public class MilkDecorator extends Decorator{
    5. public MilkDecorator(Coffee coffee){
    6. super(coffee);
    7. }
    8. /**
    9. * 获取咖啡名称
    10. */
    11. public String getName(){
    12. return coffee.getName()+",加牛奶";
    13. }
    14. /**
    15. * 获取咖啡价格
    16. */
    17. public Double getPrice(){
    18. return coffee.getPrice()+1.5;
    19. }
    20. }
    21. /**
    22. * 糖-装饰器
    23. */
    24. public class SugarDecorator extends Decorator{
    25. public SugarDecorator(Coffee coffee){
    26. super(coffee);
    27. }
    28. /**
    29. * 获取咖啡名称
    30. */
    31. public String getName(){
    32. return coffee.getName()+",加糖";
    33. }
    34. /**
    35. * 获取咖啡价格
    36. */
    37. public Double getPrice(){
    38. return coffee.getPrice()+0.2;
    39. }
    40. }

    5、测试

    1. /**
    2. * 测试装饰器模式
    3. */
    4. public class TestDecorator {
    5. public static void main(String [] args){
    6. Coffee coffee = new LanShanCoffee();
    7. coffee = new MilkDecorator(coffee);
    8. coffee = new SugarDecorator(coffee);
    9. System.out.println(coffee.getName());
    10. System.out.println(coffee.getPrice());
    11. Coffee coffee1 = new MaoShiCoffee();
    12. coffee1 = new MilkDecorator(coffee1);
    13. System.out.println(coffee1.getName());
    14. System.out.println(coffee1.getPrice());
    15. }
    16. }

    测试结果:
    image.png