Loading

[设计模式]装饰者模式

抽象构件

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

posted @   Duancf  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示