Sobes.tech
Middle

What is a decorator?

sobes.tech AI

Answer from AI

Decorator is a structural design pattern that allows adding new functionality to an object dynamically without changing its structure. It wraps the object, providing the same interface as the wrapped object, while adding or modifying its behavior.

Main elements:

  • Component: An interface or abstract class defining common functionality for wrapped objects and decorators.
  • Concrete Component: The implementation of the component, the base object to which functionality is added.
  • Decorator: An abstract class implementing the Component interface and containing a reference to a Component object.
  • Concrete Decorator: An implementation of the Decorator that adds specific functionality before or after calling the wrapped object's method.

Example in Python:

# Component
class Coffee:
    def get_cost(self):
        return 5 # Base cost of coffee
    
    def get_description(self):
        return "Simple Coffee"

# Concrete Component
class SimpleCoffee(Coffee):
    pass

# Decorator
class CoffeeDecorator(Coffee):
    def __init__(self, coffee):
        self._coffee = coffee

    def get_cost(self):
        return self._coffee.get_cost()

    def get_description(self):
        return self._coffee.get_description()

# Concrete Decorator
class MilkDecorator(CoffeeDecorator):
    def get_cost(self):
        return self._coffee.get_cost() + 2 # Adding the cost of milk

    def get_description(self):
        return self._coffee.get_description() + ", Milk"

# Usage
# simple_coffee = SimpleCoffee()
# print(f"Cost: {simple_coffee.get_cost()}, Description: {simple_coffee.get_description()}")

# coffee_with_milk = MilkDecorator(simple_coffee)
# print(f"Cost: {coffee_with_milk.get_cost()}, Description: {coffee_with_milk.get_description()}")

Advantages:

  • Flexibility: Functionality can be added at runtime.
  • Avoids subclasses: Prevents creating numerous subclasses for each behavior combination.
  • Separation of concerns: Each addition of behavior is encapsulated in a separate class.

Disadvantages:

  • Can increase the number of classes.
  • Debugging may become more complex due to the chain of wrappers.
What is a decorator? — QA / QA Automation - sobes.tech