装饰器模式

目录

1.核心本质

装饰器模式和代理模式的区别:

2.组成结构

3.代码实现

3.1 coffe接口

3.2 StubkCoffee,LuckingCoffee

3.3 Milk,Sugar

3.4 测试类

4.JDK源码举例


1.核心本质

装饰器模式通过递归组合来实现对对象行为的动态增加,同时保持接口的一致性,使得客户端可以透明地使用装饰后的对象。

装饰器模式和代理模式的区别:

装饰器是用来动态增加对象的功能,通过递归实现。

代理模式是控制对象的访问,通过生成代理对象。

2.组成结构

1.抽象构建角色:coffee接口

2.具体构建角色:StubkCoffee,LuckingCoffee

3.装饰器角色:Milk,Sugar

4.具体装饰器角色:测试类 进行具体的组装

3.代码实现

3.1 coffe接口

public interface Coffee {
    String getDescription();
    double cost();
}

3.2 StubkCoffee,LuckingCoffee

public class LuckingCoffee implements Coffee{
    @Override
    public String getDescription() {
        return "LuckingCoffee";
    }

    @Override
    public double cost() {
        return 9.9;
    }
}

public class StubkCoffee implements Coffee{
    @Override
    public String getDescription() {
        return "StubkCoffee";
    }

    @Override
    public double cost() {
        return 33;
    }
}

3.3 Milk,Sugar

public class Milk implements Coffee {
    protected Coffee coffee;

    public Milk(Coffee coffee){
        this.coffee=coffee;
    }
    @Override
    public String getDescription() {
        return coffee.getDescription() + "牛奶";
    }

    @Override
    public double cost() {
        return coffee.cost() + 3;
    }
}

public class Sugar implements Coffee{
    protected Coffee coffee;

    public Sugar(Coffee coffee){
        this.coffee = coffee;
    }
    @Override
    public String getDescription() {
        return coffee.getDescription()+ "加糖";
    }

    @Override
    public double cost() {
        return coffee.cost() + 0.5;
    }
}

3.4 测试类

public class Test {
    public static void main(String[] args) {
        //星巴克  啥都不要
        StubkCoffee stubkCoffee = new StubkCoffee();
        System.out.println(stubkCoffee.getDescription()+" "+stubkCoffee.cost());

        //加糖瑞幸
        LuckingCoffee luckingCoffee = new LuckingCoffee();
        Sugar sugar = new Sugar(luckingCoffee);
        System.out.println(sugar.getDescription()+" "+sugar.cost());

        //加奶瑞幸
        Milk milk = new Milk(luckingCoffee);
        System.out.println(milk.getDescription()+" "+milk.cost());

        //加糖加奶星巴克
        Milk milk1 = new Milk(new Sugar(stubkCoffee));
        System.out.println(milk1.getDescription()+" "+milk1.cost());
    }
}

4.JDK源码举例

BufferedWriter使用装饰者模式对writer进行了增强,添加了缓冲区,提供了写数据的效率。

 public static void main(String[] args) throws Exception{
        FileWriter fileWriter = new FileWriter("test.txt");
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
        bufferedWriter.write("Hello World");
        bufferedWriter.close();
    }

  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值