设计模式学习 装饰模式
装饰模式概念如下:

使用动机

简单例子
假设一个快餐,比如炒饭。但是可以添加小菜(鸡蛋,培根)
定义快餐类(定义cost接口)
public abstract class FastFood {
private float price;
private String desc;
public FastFood() {
}
public FastFood(float price, String desc) {
this.price = price;
this.desc = desc;
}
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 abstract float cost();
}
定义炒饭(可以被额外装饰的类)
public class FiledRice extends FastFood {
public FiledRice(){
super(10,"炒饭");
}
@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 class Bacon extends Garnish {
public Bacon(FastFood fastFood) {
super(fastFood, 2,"培根");
}
@Override
public float cost() {
return getPrice()+getFastFood().getPrice();
}
public String getDesc(){
return super.getDesc()+getFastFood().getDesc();
}
}
同理定义鸡蛋
public class Egg extends Garnish {
public Egg(FastFood fastFood) {
super(fastFood, 2, "鸡蛋");
}
@Override
public float cost() {
return getPrice()+getFastFood().getPrice();
}
public String getDesc(){
return super.getDesc()+getFastFood().getDesc();
}
}
主程序
public class Client {
public static void main(String[] args) {
//点一份炒饭
FastFood food=new FiledRice();
//花费的价格
System.out.println(food.getDesc()+" "+food.cost()+"元");
System.out.println("-------");
//点一份鸡蛋抄饭
FastFood food1=new FiledRice();
food1=new Egg(food1);
//花费的价格
System.out.println(food1.getDesc()+" "+food1.cost()+"元");
//点一份培根鸡蛋饭
food1=new Bacon(food1);
//花费的价格
System.out.println(food1.getDesc()+" "+food1.cost()+"元");
}
}

总结


浙公网安备 33010602011771号