//抽象装饰类
public class WaterAdd implements Water{
private Water water;
public WaterAdd(Water water) {
this.water = water;
}
@Override
public double jiaGe() {
return this.water.jiaGe();
}
@Override
public String name() {
return this.water.name();
}
@Override
public String jieSao() {
return this.water.jieSao();
}
}
----------------------------------
//抽象组件
public interface Water {
double jiaGe(); //价格
String name();
String jieSao(); //介绍
}
----------------------------------
public class Sugers extends WaterAdd {
public Sugers(Water water) {
super(water);
}
@Override
public double jiaGe() {
return super.jiaGe()+3;
}
@Override
public String name() {
return super.name()+"红糖农夫山泉";
}
@Override
public String jieSao() {
return super.jieSao()+"加红糖的农夫山泉";
}
}
----------------------------------
//具体组件
public class SpringWaterimple implements Water {
String name = "农夫山泉";
String nameType = "农夫山泉有点甜";
@Override
public double jiaGe() {
return 3;
}
@Override
public String name() {
return name;
}
@Override
public String jieSao() {
return nameType;
}
}
----------------------------------
public class Ningmeng extends WaterAdd {
public Ningmeng(Water water) {
super(water);
}
@Override
public double jiaGe() {
return super.jiaGe() + 10;
}
@Override
public String name() {
return super.name() +"柠檬农夫山泉";
}
@Override
public String jieSao() {
return super.jieSao() + "加柠檬的农夫山泉";
}
}
----------------------------------
public class Mike extends WaterAdd {
public Mike(Water water) {
super(water);
}
@Override
public double jiaGe() {
return super.jiaGe()*3;
}
@Override
public String name() {
return super.name()+"牛奶农夫山泉";
}
@Override
public String jieSao() {
return super.jieSao()+"加牛奶的农夫山泉";
}
}
----------------------------------
public class MainTest {
public static void main(String[] args) {
Water waters = new SpringWaterimple();
Water mikes = new Mike(waters);
Sugers supers = new Sugers(mikes);
Ningmeng Ningmengs = new Ningmeng(supers);
System.err.println("价格:"+waters.jiaGe()+"\n"+"产品名称:"+waters.name()+"\n"+"产品介绍:"+waters.jieSao());
System.err.println("价格:"+mikes.jiaGe()+"\n"+"产品名称:"+mikes.name()+"\n"+"产品介绍:"+mikes.jieSao());
System.err.println("价格:"+supers.jiaGe()+"\n"+"产品名称:"+supers.name()+"\n"+"产品介绍:"+supers.jieSao());
System.err.println("价格:"+Ningmengs.jiaGe()+"\n"+"产品名称:"+Ningmengs.name()+"\n"+"产品介绍:"+Ningmengs.jieSao());
}
}
----------------------------------
返回结果
价格:3.0
产品名称:农夫山泉
产品介绍:农夫山泉有点甜
价格:9.0
产品名称:农夫山泉牛奶农夫山泉
产品介绍:农夫山泉有点甜加牛奶的农夫山泉
价格:12.0
产品名称:农夫山泉牛奶农夫山泉红糖农夫山泉
产品介绍:农夫山泉有点甜加牛奶的农夫山泉加红糖的农夫山泉
价格:22.0
产品名称:农夫山泉牛奶农夫山泉红糖农夫山泉柠檬农夫山泉
产品介绍:农夫山泉有点甜加牛奶的农夫山泉加红糖的农夫山泉加柠檬的农夫山泉
Spring装饰器设计模式
于 2022-03-01 21:25:47 首次发布