首頁  >  文章  >  Java  >  java裝飾者模式如何使用

java裝飾者模式如何使用

王林
王林轉載
2023-04-19 21:01:051009瀏覽

1、使用說明

(1)裝飾者模式可以帶來比繼承更加靈活的擴展功能,使用更加方法,可以透過組合不同的裝飾者物件來獲取具有不同行為狀態的多樣化的結果。裝飾者模式比繼承更具良好的擴展性,完美的遵循開閉原則,繼承是靜態的附加責任,裝飾者則是動態的附加責任。

(2)裝飾類別和被裝飾類別可以獨立發展,不會相互耦合,裝飾模式是繼承的一個替代模式,裝飾模式可以動態擴展一個實現類別的功能。

2、實例

public class HelloWorld {
    public static void main(String[] args) {
        //点一份炒饭
        FastFood food = new FriedRice();
        //花费的价格
        System.out.println(food.getDesc() + " " + food.cost() + "元");
 
        System.out.println("========");
 
        //点一份加鸡蛋的炒饭
        FastFood food1 = new FriedRice();
        food1 = new Egg(food1);
        //花费的价格
        System.out.println(food1.getDesc() + " " + food1.cost() + "元");
 
        System.out.println("========");
 
        //点一份加培根的炒面
        FastFood food2 = new FriedNoodles();
        food2 = new Bacon(food2);
        //花费的价格
        System.out.println(food2.getDesc() + " " + food2.cost() + "元");
    }
}
 
// 快餐抽象类
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();
}
 
// 炒饭
class FriedRice extends FastFood {
    public FriedRice() {
        super(10, "炒饭");
    }
 
    @Override
    public float cost() {
        return getPrice();
    }
}
 
// 炒面
class FriedNoodles extends FastFood {
    public FriedNoodles() {
        super(12, "炒面");
    }
 
    @Override
    public float cost() {
        return getPrice();
    }
}
 
// 配料
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;
    }
}
 
// 鸡蛋配料
class Egg extends Garnish {
    public Egg(FastFood fastFood) {
        super(fastFood, 1, "鸡蛋");
    }
 
    @Override
    public float cost() {
        return getPrice() + getFastFood().getPrice();
    }
 
    @Override
    public String getDesc() {
        return super.getDesc() + getFastFood().getDesc();
    }
}
 
//培根配料
class Bacon extends Garnish {
    public Bacon(FastFood fastFood) {
        super(fastFood,2,"培根");
    }
 
    @Override
    public float cost() {
        return getPrice() + getFastFood().getPrice();
    }
 
    @Override
    public String getDesc() {
        return super.getDesc() + getFastFood().getDesc();
    }
}

以上是java裝飾者模式如何使用的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除