/**
* @Description 具体的被装饰者,ConcreteComponent
**/
public class BigBike implements Bike{
private String description = "大号自行车";
@Override
public String getDescription() {
return description;
}
/**
* 200元是大号自行车的价格
* @return
*/
@Override
public int getPrice() {
return 200;
}
}
/**
* @Description 通用组件
**/
public interface Bike {
String getDescription();
int getPrice();
}
public class BikeDecorator implements Bike {
private String description = "我只是装饰器,啥都不表示,子类帮我传递";
@Override
public String getDescription() {
return description;
}
@Override
public int getPrice() {
return 0;
}
}
/**
* @Description RSC 是防爆胎的缩写,角色 ConcreteDecorator
**/
public class RSCBikeDecorator extends BikeDecorator {
private String description = "增加一个防爆胎";
private Bike bike;
public RSCBikeDecorator(Bike bike){
this.bike = bike;
}
@Override
public String getDescription() {
return bike.getDescription() + ","+ description;
}
/**
* 100 是防爆胎的价格
* @return
*/
@Override
public int getPrice() {
return bike.getPrice() + 100;
}
}
/**
* @Description 具体的被装饰者,ConcreteComponent
**/
public class SmallBike implements Bike{
private String description = "小号自行车";
@Override
public String getDescription() {
return description;
}
/**
* 100元是小号自行车的价格
* @return
*/
@Override
public int getPrice() {
return 200;
}
}
/**
* @Description 喇叭,角色 ConcreteDecorator
**/
public class SuonaBikeDecorator extends BikeDecorator {
private String description = "增加一个喇叭";
private Bike bike;
public SuonaBikeDecorator(Bike bike){
this.bike = bike;
}
@Override
public String getDescription() {
return bike.getDescription() + ","+ description;
}
/**
* 50 是唢呐喇叭的价格
* @return
*/
@Override
public int getPrice() {
return bike.getPrice() + 50;
}
}
public class Main {
public static void main(String[] args) {
/**
* 大自行车 200
* 小自行车 100
* 防爆胎 100
* 喇叭 50
*/
//选个自行车
Bike bike = new BigBike();
//搭配了个RSC防爆胎
bike = new RSCBikeDecorator(bike);
bike = new RSCBikeDecorator(bike);
//搭配了一个喇叭
bike = new SuonaBikeDecorator(bike);
bike = new SuonaBikeDecorator(bike);
System.out.println(bike.getDescription()+", 价格:"+bike.getPrice());
}
}