装饰者模式
发布日期:2021-05-08 20:26:19 浏览次数:20 分类:精选文章

本文共 2181 字,大约阅读时间需要 7 分钟。

装饰者模式

装饰者模式——动态地将责任附加到对象上。想要扩展功能,装饰者提供了比继承更有弹性的替代方案。

以买手抓饼为例子

抽象原料类------Material

package decorator5;public abstract class Material {       String desc;    Double price;    public String getDesc() {           return desc;    }    public void setDesc(String desc) {           this.desc = desc;    }    public Double getPrice() {           return price;    }    public void setPrice(Double price) {           this.price = price;    }    public abstract double price();}

原味饼-------Pie

package decorator5;public class Pie extends Material{       public Pie(){           setDesc("原味手抓饼噢噢5.0");        setPrice(5.0);    }    @Override    public double price() {           return 5.0;    }}

紫薯味的饼------PurplePie

package decorator5;public class PurplePie extends Material{       public PurplePie(){           setDesc("紫薯手抓饼嗷5.5");        setPrice(5.5);    }    @Override    public double price() {           return getPrice();    }}

装饰者的类------Decorator

package decorator5;public abstract class Decorator extends Material{       private Material material;    public Decorator(Material material){           this.material = material;    }    @Override    public String getDesc(){           return desc + price +"&" + material.getDesc();    }    @Override    public double price(){           return price + material.price();    }}

鸡蛋类------Egg

package decorator5;public class Egg extends Decorator{       public Egg(Material material) {           super(material);        setDesc("土鸡蛋");        setPrice(1.5);    }}

热狗类-------HotDog

package decorator5;public class HotDog extends Decorator{       public HotDog(Material material) {           super(material);        setDesc("热狗啊");        setPrice(2.5);    }}

测试------Client

package decorator5;public class Client {       public static void main(String[] args) {           Material order = new Pie();        order = new Egg(order);        System.out.println("订单的描述为:"+ order.getDesc());        System.out.println("订单的总价钱为:" + order.price());        System.out.println("=====================");        order = new HotDog(order);        System.out.println("订单的描述为:"+ order.getDesc());        System.out.println("订单的总价钱为:" + order.price());    }}

在这里插入图片描述

上一篇:反转链表
下一篇:快速排序

发表评论

最新留言

能坚持,总会有不一样的收获!
[***.219.124.196]2025年04月08日 05时26分07秒