Skip to main content

Posts

Showing posts with the label decorator

Design Patterns: Decorator

The Decorator Pattern is a structural design pattern that allows behavior to be dynamically added to individual objects, without modifying their code. It is often used to extend the functionalities of classes in a flexible and reusable way. When To Use It? You Need to Add Behavior Dynamically at Runtime.  Example: A coffee shop app where users can customize their drinks with add-ons like Milk, Sugar, Whipped Cream, etc. You Want to Avoid a Large Inheritance Tree.  If you use inheritance, each combination of behaviors would require a new subclass (e.g., CoffeeWithMilk , CoffeeWithSugar , CoffeeWithMilkAndSugar , etc.). You Want More Flexible and Reusable Code.  Different decorators can be reused independently . Example: A LoggingDecorator , CompressionDecorator , and EncryptionDecorator can be used separately or in different orders. You Follow the Open-Closed Principle.  Instead of modifying an existing class, you can extend behavior using decorators . This mak...