编辑
Component
,定义了要被装饰的具体对象。Component
接口,并持有一个 Component
的引用,代表被装饰对象。装饰者类可以在调用原方法的基础上添加额外的功能。
编辑
编辑
穿衣服是使用装饰的一个例子。 觉得冷时, 你可以穿一件毛衣。 如果穿毛衣还觉得冷, 你可以再套上一件夹克。 如果遇到下雨, 你还可以再穿一件雨衣。 所有这些衣物都 “扩展” 了你的基本行为, 但它们并不是你的一部分, 如果你不再需要某件衣物, 可以方便地随时脱掉。
final
最终关键字来限制对某个类的进一步扩展。 复用最终类已有行为的唯一方法是使用装饰模式: 用封装器对其进行封装。
编辑
// 抽象构建者
public abstract class FastFood {
private float price;
private String 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 FastFood(float price, String desc) {
this.price = price;
this.desc = desc;
}
public FastFood() {}
public abstract float cost();
}
// 具体构建者
public class FriedRice extends FastFood{
public FriedRice() {
super(10, "fried rice");
}
@Override
public float cost() {
return getPrice();
}
}
// 具体构建者
public class FriedNoodles extends FastFood{
public FriedNoodles() {
super(12, "fried noodles");
}
@Override
public float cost() {
return getPrice();
}
}
// 抽象装饰者
public abstract class Garnish extends FastFood{
// 持有一个快餐的引用
private FastFood fastFood;
public Garnish(FastFood fastFood, float price, String desc) {
super(price, desc);
this.fastFood = fastFood;
}
public FastFood getFastFood() {
return fastFood;
}
public void setFastFood(FastFood fastFood) {
this.fastFood = fastFood;
}
}
// 具体装饰者
public class Egg extends Garnish{
public Egg(FastFood fastFood) {
super(fastFood, 1, "egg");
}
@Override
public float cost() {
return getPrice() + getFastFood().cost();
}
@Override
public String getDesc() {
return super.getDesc() + " " + getFastFood().getDesc();
}
}
// 具体装饰者
public class Bacon extends Garnish{
public Bacon(FastFood fastFood) {
super(fastFood, 2, "bacon");
}
@Override
public float cost() {
return getPrice() + getFastFood().cost();
}
@Override
public String getDesc() {
return super.getDesc() + " " + getFastFood().getDesc();
}
}
// 客户端
public class Client {
public static void main(String[] args) {
// 点一份炒饭
FastFood friedRice = new FriedRice();
System.out.println(friedRice.getDesc() + ":" + friedRice.cost());
System.out.println("-----------------------------------------");
// 加一个鸡蛋
friedRice = new Egg(friedRice);
System.out.println(friedRice.getDesc() + ":" + friedRice.cost());
// 加一个培根
friedRice = new Bacon(friedRice);
System.out.println(friedRice.getDesc() + ":" + friedRice.cost());
System.out.println("-----------------------------------------");
// 再加一个鸡蛋
friedRice = new Egg(friedRice);
System.out.println(friedRice.getDesc() + ":" + friedRice.cost());
}
}
编辑
编辑
参与评论
手机查看
返回顶部