概念
是指在不改变原有对象的基础上,将功能附加到对象上,提供了比继承更有弹性的替代方案(拓展原有对象功能),属于结构型设计模式
使用场景
1.用于拓展一个类的功能或给一个类添加附加职责
2.动态的给一个对象添加功能,这些功能可以再动态撤销。
实例
现场建一个抽象类型,比如蛋糕
public abstract class Cake {
protected abstract String getMsg();
protected abstract int price();
}
那么就会有一个基础蛋糕
public class BaseCake extends Cake {
@Override
protected String getMsg() {
return "小蛋糕";
}
@Override
protected int price() {
return 5;
}
}
再创建一个装饰器
public abstract class DecoratorCake extends Cake {
public Cake cake;
public DecoratorCake(Cake cake) {
this.cake = cake;
}
@Override
protected String getMsg() {
return this.cake.getMsg();
}
@Override
protected int price() {
return this.cake.price();
}
}
再来一个水果蛋糕装饰器
public class DecoratorFruitsCake extends DecoratorCake{
public DecoratorFruitsCake(Cake cake) {
super(cake);
}
@Override
protected String getMsg() {
return "一个水果"+super.getMsg();
}
@Override
protected int price() {
return 1+super.price();
}
}
最后测试一下
public class Test {
public static void main(String[] args) {
Cake cake = new BaseCake();
cake = new DecoratorFruitsCake(cake);
System.out.println(cake.getMsg());
System.out.println(cake.price());
cake = new DecoratorFruitsCake(cake);
System.out.println(cake.getMsg());
System.out.println(cake.price());
}
}
结果
一个水果小蛋糕
6
一个水果一个水果小蛋糕
7