The decorator pattern is a structural design pattern that allows dynamically adding object functionality without modifying the original class. It is implemented through the collaboration of abstract components, concrete components, abstract decorators and concrete decorators, and can flexibly expand class functions to meet changing needs. In this example, milk and mocha decorators are added to Espresso for a total price of $2.29, demonstrating the power of the decorator pattern in dynamically modifying the behavior of objects.
Analysis of the Decorator Pattern in Java Design Patterns
Introduction
Decorator A pattern is a structural design pattern that allows functionality to be dynamically added to an object without modifying its base class. By using decorator objects, class functionality can be flexibly extended to meet changing needs.
Principle
The decorator pattern works in the following way:
Code Example
// 抽象组件 interface Beverage { double cost(); } // 具体组件 class Espresso implements Beverage { @Override public double cost() { return 1.99; } } // 抽象装饰器 abstract class CondimentDecorator implements Beverage { protected Beverage beverage; public CondimentDecorator(Beverage beverage) { this.beverage = beverage; } } // 具体装饰器 class Milk extends CondimentDecorator { public Milk(Beverage beverage) { super(beverage); } @Override public double cost() { return beverage.cost() + 0.10; } } // 具体装饰器 class Mocha extends CondimentDecorator { public Mocha(Beverage beverage) { super(beverage); } @Override public double cost() { return beverage.cost() + 0.20; } } // 实战案例 public class CoffeeShop { public static void main(String[] args) { Beverage espresso = new Espresso(); // 添加牛奶和摩卡装饰器 Beverage milkEspresso = new Milk(espresso); Beverage mochaMilkEspresso = new Mocha(milkEspresso); // 计算饮料总价 double totalCost = mochaMilkEspresso.cost(); System.out.println("Beverage cost: " + totalCost); } }
Output:
Beverage cost: 2.29
Conclusion
The decorator pattern can be used to dynamically extend object functionality without modifying existing code. It provides a flexible and elegant way to meet changing needs while keeping the code maintainable and extensible.
The above is the detailed content of Analysis of the Decorator Pattern in Java Design Patterns. For more information, please follow other related articles on the PHP Chinese website!