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());
}
}