装饰者模式(代码简单介绍)
装饰者模式(Decorator Pattern)是一种结构型设计模式,它允许你动态地将行为添加到对象中,同时又不改变其原有的接口。装饰者模式通过将对象包装在一个装饰器类中,以扩展其功能。
在装饰者模式中,有以下几个核心角色:
-
抽象组件(Component):定义了被装饰者和装饰者的共同接口,可以是抽象类或接口。
-
具体组件(Concrete Component):实现了抽象组件接口,是被装饰者,也是装饰器所装饰的对象。
-
抽象装饰器(Decorator):实现了抽象组件接口,并持有一个被装饰者对象的引用,可以通过构造函数注入或setter方法注入。
-
具体装饰器(Concrete Decorator):扩展了抽象装饰器,实现了具体的装饰逻辑。
以下是一个使用Java代码实现的装饰者模式示例:
// 抽象组件 interface Coffee { String getDescription(); double getCost(); } // 具体组件 class SimpleCoffee implements Coffee { public String getDescription() { return "Simple Coffee"; } public double getCost() { return 1.0; } }
// 抽象装饰器 abstract class CoffeeDecorator implements Coffee { protected Coffee decoratedCoffee; public CoffeeDecorator(Coffee decoratedCoffee) { this.decoratedCoffee = decoratedCoffee; } public String getDescription() { return decoratedCoffee.getDescription(); } public double getCost() { return decoratedCoffee.getCost(); } } // 具体装饰器 class MilkDecorator extends CoffeeDecorator { public MilkDecorator(Coffee decoratedCoffee) { super(decoratedCoffee); } public String getDescription() { return super.getDescription() + ", with Milk"; } public double getCost() { return super.getCost() + 0.5; } } class SugarDecorator extends CoffeeDecorator { public SugarDecorator(Coffee decoratedCoffee) { super(decoratedCoffee); } public String getDescription() { return super.getDescription() + ", with Sugar"; } public double getCost() { return super.getCost() + 0.2; } }
// 示例 public class DecoratorPatternExample { public static void main(String[] args) { Coffee simpleCoffee = new SimpleCoffee(); System.out.println("Simple Coffee - Cost: $" + simpleCoffee.getCost() + ", Description: " + simpleCoffee.getDescription()); Coffee coffeeWithMilk = new MilkDecorator(simpleCoffee); System.out.println("Coffee with Milk - Cost: $" + coffeeWithMilk.getCost() + ", Description: " + coffeeWithMilk.getDescription()); Coffee coffeeWithMilkAndSugar = new SugarDecorator(coffeeWithMilk); System.out.println("Coffee with Milk and Sugar - Cost: $" + coffeeWithMilkAndSugar.getCost() + ", Description: " + coffeeWithMilkAndSugar.getDescription()); } }
在上述示例中,
我们首先定义了一个抽象组件Coffee,它定义了获取咖啡描述和价格的方法。
然后,我们实现了具体组件SimpleCoffee,它表示简单的咖啡。
接下来,我们定义了抽象装饰器CoffeeDecorator,它继承了Coffee接口并持有一个被装饰者的引用。
然后,我们实现了具体装饰器MilkDecorator和SugarDecorator,它们都扩展了CoffeeDecorator。这些具体装饰器在原有咖啡的基础上添加了额外的功能,例如添加牛奶或糖。
在示例中,我们首先创建了一个简单的咖啡对象simpleCoffee,然后通过创建装饰器对象来装饰它。我们创建了一个带有牛奶的咖啡对象coffeeWithMilk,以及一个带有牛奶和糖的咖啡对象coffeeWithMilkAndSugar。
最后,我们打印出每个咖啡对象的描述和价格。
输出结果如下:
Simple Coffee - Cost: $1.0, Description: Simple Coffee
Coffee with Milk - Cost: $1.5, Description: Simple Coffee, with Milk
Coffee with Milk and Sugar - Cost: $1.7, Description: Simple Coffee, with Milk, with Sugar
从输出可以看出,装饰者模式允许我们在不改变原有对象接口的情况下,动态地为对象添加新的行为或功能。通过装饰器的嵌套组合,我们可以实现更复杂的装饰效果,以满足不同的需求。

浙公网安备 33010602011771号