再说装饰器模式

To extend or modify the behaviour of an instance at runtime decorator design pattern is used. Inheritance is used to extend the abilities of a class. Unlike inheritance, you can choose any single object of a class and modify its behaviour leaving the other instances unmodified.

这是我们生活中一种常见的美味,其制作过程就是一种典型的装饰器模式,除了原味,我们可以额外添加坚果、草莓等额外的美味,同时还保持了原有冰淇淋的美味。

这里写图片描述

装饰器模式的UML类图

这里写图片描述

  • 定义冰淇淋制作接口Icecream
public interface Icecream {
    String makeIcecream();
}
  • 原味冰淇淋:SimpleIcecream
public class SimpleIcecream implements Icecream {

  @Override
  public String makeIcecream() {
    return "Base Icecream";
  }

}
  • 冰淇淋装饰器抽象类
abstract public class IcecreamDecorator implements Icecream {
    protected Icecream specialIcecream;

    public IcecreamDecorator(Icecream specialIcecream) {
        this.specialIcecream = specialIcecream;
    }

    public String makeIcecream() {
        return specialIcecream.makeIcecream();
    }

}
  • 坚果冰淇淋装饰
public class NuttyDecorator extends IcecreamDecorator {
    public NuttyDecorator(Icecream specialIcecream) {
        super(specialIcecream);
    }

    public String makeIcecream() {
        System.out.println("NuttyDecorator makeIcecream");
        return specialIcecream.makeIcecream() + addNuts();
    }

    private String addNuts() {
        return " + cruncy nuts";
    }
}
  • 草莓冰淇淋装饰
public class StrawberryDecorator extends IcecreamDecorator {
    public StrawberryDecorator(Icecream specialIcecream) {
        super(specialIcecream);
    }

    public String makeIcecream() {
        System.out.println("StrawberryDecorator makeIcecream");
        return super.makeIcecream() + " + strawberry";
    }
}
  • 可爱甜心冰淇淋装饰
public class HoneyDecorator extends IcecreamDecorator {

    public HoneyDecorator(Icecream specialIcecream) {
        super(specialIcecream);
    }

    public String makeIcecream() {
        System.out.println("HoneyDecorator makeIcecream");
        return specialIcecream.makeIcecream() + addHoney();
    }

    private String addHoney() {
        return " + sweet honey";
    }
}
  • 最后我们来制作一个多味的冰淇淋,同时添加了坚果、草莓与可爱甜心
public class TestDecorator {
    public static void main(String args[]) {

        Icecream icecream = new StrawberryDecorator(new HoneyDecorator(new NuttyDecorator(new SimpleIcecream())));
        System.out.println(icecream.makeIcecream());

    }
}

https://javapapers.com/design-patterns/decorator-pattern/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值