参考:https://blog.csdn.net/weixin_48052161/article/details/118111642
装饰器模式就是为原有类添加新的东西如:在构造上和方法上;但满足对扩展开发对修改关闭原则!
对蛋糕进行装饰模式装饰,而装饰器又使用了策略模式进行分类处理!
蛋糕抽象类:
package com.example.dtest.design23.decorator;
import java.math.BigDecimal;
public abstract class Cake {
public abstract String getCakeMsg();
public abstract BigDecimal getPrice();
}
基础蛋糕类:
package com.example.dtest.design23.decorator;
import java.math.BigDecimal;
public class BaseCake extends Cake{
@Override
public String getCakeMsg() {
return "我是一个8英寸的普通蛋糕";
}
@Override
public BigDecimal getPrice() {
return new BigDecimal("68");
}
}
蛋糕装饰器抽象类:
package com.example.dtest.design23.decorator;
import java.math.BigDecimal;
public abstract class CakeDecorator extends Cake{
private Cake cake;
public CakeDecorator(Cake cake){
this.cake = cake;
}
@Override
public String getCakeMsg() {
return this.cake.getCakeMsg()+"-初级装饰-";
}
@Override
public BigDecimal getPrice() {
return this.cake.getPrice().add(new BigDecimal("0"));
}
}
装饰器实现装饰器类继而实现蛋糕修饰:
修饰1:芒果修饰
package com.example.dtest.design23.decorator;
import java.math.BigDecimal;
public class CakeAddMangoDecorator extends CakeDecorator{
public CakeAddMangoDecorator(Cake cake) {
super(cake);
}
public String getCakeMsg(){
return super.getCakeMsg()+"+1个芒果";
}
public BigDecimal getPrice(){
return super.getPrice().add(new BigDecimal("10"));
}
}
修饰2:草莓修饰
package com.example.dtest.design23.decorator;
import java.math.BigDecimal;
public class CakeAddCrapeDecorator extends CakeDecorator{
public CakeAddCrapeDecorator(Cake cake) {
super(cake);
}
public String getCakeMsg(){
return super.getCakeMsg()+"+1个葡萄";
}
public BigDecimal getPrice(){
return super.getPrice().add(new BigDecimal("5"));
}
}
测试类:
package com.example.dtest.design23.decorator;
public class DecoratorTest {
public static void main(String[] args) {
Cake cake = null;
//普通蛋糕
cake = new BaseCake();
System.out.println(cake.getCakeMsg() + ",价格:" + cake.getPrice());
//加一个芒果
cake = new CakeAddMangoDecorator(cake);
System.out.println(cake.getCakeMsg() + ",价格:" + cake.getPrice());
//加一个葡萄
cake = new CakeAddCrapeDecorator(cake);
System.out.println(cake.getCakeMsg() + ",价格:" + cake.getPrice());
//再加一个芒果
cake = new CakeAddMangoDecorator(cake);
System.out.println(cake.getCakeMsg() + ",价格:" + cake.getPrice());
}
}
只表示装饰模式,功能在第一个装饰抽象就可以完成了!!!!
装饰器模式主要为类扩展方法和构造等,因为它聚合了要装饰的对象!!