[設計模式]裝飾者模式

Duancf發表於2024-08-09

抽象構件

public abstract class FastFood {

    public String desc;
    public int price;

    public abstract String getDesc();

    public abstract int getPrice();

}

具體構件

米飯

public class Rice extends FastFood {

    public Rice() {
        this.desc = "米飯";
        this.price = 10;
    }

    @Override
    public String getDesc() {
        return this.desc;
    }

    @Override
    public int getPrice() {
        return this.price;
    }
}

麵條

public class Noddle extends FastFood {

    public Noddle() {
        this.desc = "麵條";
        this.price = 8;
    }

    @Override
    public String getDesc() {
        return this.desc;
    }

    @Override
    public int getPrice() {
        return this.price;
    }
}

抽象裝飾器

public abstract class SideFood extends FastFood {

    FastFood fastFood;

    public SideFood(FastFood fd) {
        this.fastFood = fd;
    }

    @Override
    public String getDesc() {
        return this.fastFood.getDesc();
    }

    @Override
    public int getPrice() {
        return this.fastFood.getPrice();
    }
}

具體裝飾器

雞蛋

public class Egg extends SideFood {
    public Egg(FastFood fd) {
        super(fd);
    }

    @Override
    public String getDesc() {
        return this.fastFood.getDesc() + "加雞蛋";
    }

    @Override
    public int getPrice() {
        return this.fastFood.getPrice() + 5;
    }
}

火腿

public class Ham extends SideFood {
    public Ham(FastFood fd) {
        super(fd);
    }

    @Override
    public String getDesc() {
        return this.fastFood.getDesc() + "加火腿";
    }

    @Override
    public int getPrice() {
        return this.fastFood.getPrice() + 8;
    }
}

使用案例

public class Main {
    public static void main(String[] args) {

        Rice rice = new Rice();
        Egg egg = new Egg(rice);
        Ham ham = new Ham(egg);

        System.out.println(ham.getDesc());
        System.out.println(ham.getPrice());

    }
}

類圖

image

相關文章