Monday, August 1, 2016

Decorator design pattern

Decorator pattern is one of the widely used structural patterns. This pattern dynamically changes the functionality of an object at run-time without impacting the existing functionality of the objects. 
The Decorator pattern is used to extend the functionalities of a class.

Example

1. Suppose you have a basic coffee class and want to add various condiments (e.g., milk, sugar) dynamically.

2. Imagine a scenario where we have a pizza which is already baked with tomato and cheese. After that you just recall that you need to put some additional topping at customer’s choice. So, you will need to give some additional toppings like chicken and pepper on the go.

Benefits:
Decorator design pattern provides more flexibility than the standard inheritance. Inheritance also extends the parent class responsibility but in a static manner. However, decorator allows doing this in dynamic fashion.

There are various live examples of decorator pattern in Java API.
    1. java.io.BufferedReader;
    2. java.io.FileReader;
    3. java.io.Reader;

Here are some real-time use cases for the Decorator Design Pattern:

1. Logging and Monitoring

  • Scenario: An application needs to log messages in different formats (e.g., plain text, JSON) and with additional metadata (e.g., timestamps, log levels) without modifying the core logging logic.
  • Decorator Use Case: Create decorators like TimestampDecorator, LogLevelDecorator, and JsonFormatDecorator that wrap around a base Logger class. This enables flexible and modular logging enhancements.

2. E-Commerce Platforms

  • Scenario: An e-commerce platform needs to apply various pricing strategies, discounts, and promotions to products dynamically.
  • Decorator Use Case: Implement decorators like DiscountDecorator, CouponDecorator, and SeasonalOfferDecorator that wrap around a base Product class. This approach allows you to add or change pricing strategies without modifying the core product logic.

3. File Compression

  • Scenario: A file compression utility needs to support various compression algorithms (e.g., ZIP, RAR, GZIP) and additional features like encryption.
  • Decorator Use Case: Implement decorators such as ZipCompressionDecorator, RarCompressionDecorator, and EncryptionDecorator that wrap around a base FileCompressor class. This allows you to add new compression algorithms or features without altering the core compression logic.

 

No comments:

Post a Comment