装饰者模式和静态代理模式的相同
相同点
1.都要是实现目标接口
2.在两个类中都要实现目标对象
3.都可以在不改变目标类的前提下增强目标方法
不同点
1.目的不同
装饰者模式重在加强目标类的方法和功能
代理类重在保护目标类
2.获取目标对象的地点不同
装饰者是从外界传入的对象
代理模式是内部生成的对象
//装饰着模式
//抽象构建角色
public abstract class FastFood {
private float price;
private String desc;
public FastFood(float price, String desc) {
this.price = price;
this.desc = desc;
}
public FastFood() {
}
public abstract float cost();
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
/**
* 具体构建角色
*/
public class FriedRice extends FastFood{
public FriedRice(){
super(10,"炒饭");
}
@Override
public float cost() {
return getPrice();
}
}
public class FriedNoodle extends FastFood {
public FriedNoodle(){
super(12,"炒面");
}
@Override
public float cost() {
return getPrice();
}
}
/**
* 装饰着类
*/
public abstract class Garnish extends FastFood {
private FastFood fastFood;
public FastFood getFastFood() {
return fastFood;
}
public void setFastFood(FastFood fastFood) {
this.fastFood = fastFood;
}
public Garnish( FastFood fastFood,float price, String desc) {
super(price, desc);
this.fastFood = fastFood;
}
public Garnish(FastFood fastFood) {
this.fastFood = fastFood;
}
}
public class Egg extends Garnish {
public Egg(FastFood fastFood){
super(fastFood,1,"鸡蛋");
}
public static void main(String[] args) {
FastFood friedRice = new FriedRice();
System.out.println(friedRice.getDesc()+"价格为:"+friedRice.cost());
friedRice=new Egg(friedRice);
System.out.println(friedRice.getDesc()+"价格为:"+friedRice.cost());
friedRice=new Egg(friedRice);
System.out.println(friedRice.getDesc()+"价格为:"+friedRice.cost());
}
//加鸡蛋后的价格
@Override
public float cost() {
return getPrice()+getFastFood().cost();
}
@Override
public String getDesc() {
return super.getDesc()+getFastFood().getDesc();
}
}