个人理解:为一个是事物不断地包装,每包装一层,都会把上一层算上(前提是他们都继承同一个基类)(super)
定义:动态的将责任附加到对象上。若要扩展功能,装饰者提供了比继承更有弹性的替代方案.
代码:
汉堡基类
public abstract class Humburger{
protect String name;
public String getName(){
return name;
}
public abstract double getPrice();
}
鸡腿汉堡
public class chickenBurger extends Humburger{
public ChickenBurger(){
name = "鸡腿堡";
}
@Override
public double getPrice(){
return 10;
}
}
配菜的基类
public abstract class Condmient extends Humburger{
public abstract String getName();
}
生菜类
public class Letturce extends Condiment{
Humber humber;
public Letture(Humburger humburger){
this.humburger = humburger;
}
@Override
public String getName(){
return humburger.getName()+"生菜";
}
@Override
public double getPrice(){
return humburger.getPrice+1.5;
}
}
辣椒
public class Chilli extends Condiment{
Humburger humburger;
public Chilli(Humburger humburger){
this.humburger = humburger;
}
@Override
public String getName(){
return humburger.getName()+"加辣椒";
}
@Override
public double getPrice(){
return humburget.getPrice();//辣椒是免费的
}
}