侧边栏壁纸
博主头像
人生短短几个秋

行动起来,活在当下

  • 累计撰写 45 篇文章
  • 累计创建 20 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

设计模式-装饰器模式

人生短短几个秋
2025-01-25 / 0 评论 / 0 点赞 / 15 阅读 / 0 字

设计模式 - 装饰器模式(Decorator Pattern)

介绍

装饰器模式是一种结构型设计模式,它允许向对象添加新的功能,同时保持类的其他行为不变。这种模式通过创建一个包装对象,也就是装饰来包裹真实的对象。装饰器模式是面向对象编程中一个非常有用的工具,尤其是在需要扩展类的功能或者添加责任到类的行为上。

实现

我们以一个简单的咖啡店为例,说明如何使用装饰器模式来动态地为一杯咖啡添加不同的配料。

定义组件接口

首先,定义一个基本的组件接口,所有饮料(包括基本饮料和装饰后的饮料)都必须实现这个接口。

interface Beverage {
    String getDescription();
    double cost();
}

创建具体饮料

接下来,创建几个具体的饮料类,它们实现了 Beverage 接口。

abstract class BaseBeverage implements Beverage {
    String description = "Unknown beverage";

    public String getDescription() {
        return description;
    }

    public abstract double cost();
}

class HouseBlend extends BaseBeverage {
    public HouseBlend() {
        description = "House Blend Coffee";
    }

    public double cost() {
        return .89;
    }
}

class DarkRoast extends BaseBeverage {
    public DarkRoast() {
        description = "Dark Roast Coffee";
    }

    public double cost() {
        return .99;
    }
}

创建装饰器

装饰器类同样实现了 Beverage 接口,并且持有被装饰对象的引用。

abstract class CondimentDecorator implements Beverage {
    protected Beverage beverage;

    public abstract String getDescription();
}

class Milk extends CondimentDecorator {
    public Milk(Beverage beverage) {
        this.beverage = beverage;
    }

    public String getDescription() {
        return beverage.getDescription() + ", Milk";
    }

    public double cost() {
        return .10 + beverage.cost();
    }
}

class Soy extends CondimentDecorator {
    public Soy(Beverage beverage) {
        this.beverage = beverage;
    }

    public String getDescription() {
        return beverage.getDescription() + ", Soy";
    }

    public double cost() {
        return .15 + beverage.cost();
    }
}

使用装饰器模式

最后,在主程序中使用装饰器模式来为咖啡添加不同的配料。

public class CoffeeShop {
    public static void main(String[] args) {
        Beverage baseCoffee = new HouseBlend();
        System.out.println(baseCoffee.getDescription() + " $" + baseCoffee.cost());

        // 添加牛奶
        Beverage coffeeWithMilk = new Milk(baseCoffee);
        System.out.println(coffeeWithMilk.getDescription() + " $" + coffeeWithMilk.cost());

        // 添加豆奶
        Beverage coffeeWithSoy = new Soy(baseCoffee);
        System.out.println(coffeeWithSoy.getDescription() + " $" + coffeeWithSoy.cost());
    }
}

使用场景

装饰器模式适用于:

  • 在不影响其他对象的情况下,以动态透明的方式给单个对象添加职责。
  • 处理那些可以撤消的职责。
  • 当不能采用生成子类的方法进行扩充时。

总结

装饰器模式允许我们通过创建装饰类来扩展对象的功能,而不是通过继承来扩展。这种方式提供了比继承更大的灵活性,因为可以在运行时动态地添加责任。此外,装饰器模式还允许通过组合多个装饰器来创建复杂的行为层次结构。


以上就是装饰器模式的一个实现案例,希望这篇文章能帮助你理解装饰器模式的使用方式及其优势。

0

评论区