结构型模式-装饰器模式

文章介绍了装饰者模式在解决快餐店菜单扩展性问题上的应用。通过装饰者模式,可以避免因添加新配料或菜品而频繁创建新的子类,提高了代码的扩展性和灵活性。文中给出了具体的Java代码示例,展示如何使用装饰者模式来计算不同组合的快餐价格。此外,还提到了JavaIO流中的包装类如BufferedWriter作为装饰者模式的例子,并对比了装饰者与静态代理的区别。
摘要由CSDN通过智能技术生成

1.概述

快餐店有炒面、炒饭这些快餐,可以额外附加鸡蛋、火腿、培根这些配菜,当然加配菜需要额外加钱,每个配菜的价钱通常不太一样,那么计算总价就会显得比较麻烦。

使用继承的方式存在的问题:

  • 扩展性不好
    如果要再加一种配料(火腿肠),我们就会发现需要给FriedRice和FriedNoodles分别定义一个子类。如果要新增一个快餐品类(炒河粉)的话,就需要定义更多的子类。
  • 产生过多的子类

定义:指在不改变现有对象结构的情况下,动态地给该对象增加一些职责(即增加其额外功能)的模式。

2.结构

装饰(Decorator)模式中的角色:

  • 抽象构件(Component)角色 :定义一个抽象接口以规范准备接收附加责任的对象。
  • 具体构件(Concrete Component)角色 :实现抽象构件,通过装饰角色为其添加一些职责。
  • 抽象装饰(Decorator)角色 : 继承或实现抽象构件,并包含具体构件的实例,可以通过其子类扩展具体构件的功能。
  • 具体装饰(ConcreteDecorator)角色 :实现抽象装饰的相关方法,并给具体构件对象添加附加的责任。

3.案例

我们使用装饰者模式对快餐店案例进行改进,体会装饰者模式的精髓。
类图如下
在这里插入图片描述
代码如下

package com.itheima.pattern.decorator;

/**
 * @program: design-patterns
 * @ClassName FastFood
 * @description: 快餐类(抽象构建Component角色)
 * @author: 
 * @create: 2023-01-15 16:29
 * @Version 1.0
 **/
public 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();
}
package com.itheima.pattern.decorator;

/**
 * @program: design-patterns
 * @ClassName Egg
 * @description: 培根类:具体装饰(ConcreteDecorator)角色
 * @author: 
 * @create: 2023-01-15 16:40
 * @Version 1.0
 **/
public class Bacon extends Garnish {

    public Bacon(FastFood fastFood) {
        super(2, "培根", fastFood);
    }

    @Override
    public float cost() {
        // 计算价格
        return getPrice() + getFastFood().cost();
    }

    @Override
    public String getDesc() {
        // 描述信息
        return super.getDesc() + getFastFood().getDesc();
    }
}
package com.itheima.pattern.decorator;

/**
 * @program: design-patterns
 * @ClassName Egg
 * @description: 鸡蛋类:具体装饰(ConcreteDecorator)角色
 * @author: 
 * @create: 2023-01-15 16:40
 * @Version 1.0
 **/
public class Egg extends Garnish {

    public Egg(FastFood fastFood) {
        super(1, "鸡蛋", fastFood);
    }

    @Override
    public float cost() {
        // 计算价格
        return getPrice() + getFastFood().cost();
    }

    @Override
    public String getDesc() {
        return super.getDesc() + getFastFood().getDesc();
    }
}
package com.itheima.pattern.decorator;

/**
 * @program: design-patterns
 * @ClassName FriedNoodles
 * @description: 炒面:具体构件(Concrete Component)角色
 * @author: 
 * @create: 2023-01-15 16:35
 * @Version 1.0
 **/
public class FriedNoodles extends FastFood {

    public FriedNoodles() {
        super(11, "炒面");
    }

    @Override
    public float cost() {
        return getPrice();
    }
}
package com.itheima.pattern.decorator;

/**
 * @program: design-patterns
 * @ClassName FriedRice
 * @description: 炒饭:具体构件(Concrete Component)角色
 * @author: 
 * @create: 2023-01-15 16:32
 * @Version 1.0
 **/
public class FriedRice extends FastFood {

    public FriedRice() {
        super(10, "炒饭");
    }

    @Override
    public float cost() {
        return getPrice();
    }
}
package com.itheima.pattern.decorator;

/**
 * @program: design-patterns
 * @ClassName Garnish
 * @description: 装饰者类:抽象装饰(Decorator)角色
 * @author: 
 * @create: 2023-01-15 16:37
 * @Version 1.0
 **/
public abstract class Garnish extends FastFood {
    // 声明快餐类的变量
    private FastFood fastFood;

    public Garnish(float price, String desc, FastFood fastFood) {
        super(price, desc);
        this.fastFood = fastFood;
    }

    public FastFood getFastFood() {
        return fastFood;
    }

    public void setFastFood(FastFood fastFood) {
        this.fastFood = fastFood;
    }
}
package com.itheima.pattern.decorator;

/**
 * @program: design-patterns
 * @ClassName Client
 * @description: 测试类
 * @author: 
 * @create: 2023-01-15 16:45
 * @Version 1.0
 **/
public class Client {
    public static void main(String[] args) {
        FastFood rice = new FriedRice();
        System.out.println(rice.getDesc() + " " + rice.cost() + "元");
        System.out.println("====================");
        // 在上面的炒饭中加一个鸡蛋
        FastFood rice1 = new Egg(rice);
        System.out.println(rice1.getDesc() + " " + rice1.cost() + "元");

        System.out.println("====================");
        // 在上面的炒饭中加一份培根
        FastFood bacon = new Bacon(rice);
        System.out.println(bacon.getDesc() + " " + bacon.cost() + "元");
    }
}

好处:

  • 饰者模式可以带来比继承更加灵活性的扩展功能,使用更加方便,可以通过组合不同的装饰者对象来获取具有不同行为状态的多样化的结果。装饰者模式比继承更具良好的扩展性,完美的遵循开闭原则,继承是静态的附加责任,装饰者则是动态的附加责任。
  • 装饰类和被装饰类可以独立发展,不会相互耦合,装饰模式是继承的一个替代模式,装饰模式可以动态扩展一个实现类的功能。

4.使用场景

  • 当不能采用继承的方式对系统进行扩充或者采用继承不利于系统扩展和维护时。
    不能采用继承的情况主要有两类:
    (1)第一类是系统中存在大量独立的扩展,为支持每一种组合将产生大量的子类,使得子类数目呈爆炸性增长;
    (2)第二类是因为类定义不能继承(如final类)
  • 在不影响其他对象的情况下,以动态、透明的方式给单个对象添加职责。
  • 当对象的功能要求可以动态地添加,也可以再动态地撤销时。

5.JDK源码解析

IO流中的包装类使用到了装饰者模式。BufferedInputStream,BufferedOutputStream,BufferedReader,BufferedWriter。
我们以BufferedWriter举例来说明,先看看如何使用BufferedWriter

public class Demo {
	public static void main(String[] args) throws Exception{
		//创建BufferedWriter对象
		//创建FileWriter对象
		FileWriter fw = new FileWriter("C:\\Users\\Think\\Desktop\\a.txt");
		BufferedWriter bw = new BufferedWriter(fw);
		//写数据
		bw.write("hello Buffered");
		bw.close();
	}
}

使用起来感觉确实像是装饰者模式,接下来看它们的结构:
在这里插入图片描述

小结:BufferedWriter使用装饰者模式对Writer子实现类进行了增强,添加了缓冲区,提高了写数据的效率。

6.代理和装饰者的区别

静态代理和装饰者模式的区别:

  • 相同点
    (1)都要实现与目标类相同的业务接口
    (2)在两个类中都要声明目标对象
    (3)都可以在不修改目标类的前提下增强目标方法
  • 不同点
    (1)目的不同 装饰者是为了增强目标对象 静态代理是为了保护和隐藏目标对象
    (2)获取目标对象构建的地方不同 装饰者是由外界传递进来,可以通过构造方法传递 静态代理是在代理类内部创建,以此来隐藏目标对象
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值