Sobes.tech
Junior — Middle

In what cases and for what purpose is the Decorator pattern used in programming?

sobes.tech AI

Answer from AI

The Decorator pattern is used for dynamically adding new responsibilities to an object without changing its original code. This allows for flexible and transparent extension of object functionality for the client.

It is applied when you need to add behavior to an object at runtime, avoiding the creation of numerous subclasses for each combination of features.

In Python, a decorator is often implemented through classes or functions that wrap the original object.

Example of the Decorator pattern in Python:

class Coffee:
    def cost(self):
        return 5

class MilkDecorator:
    def __init__(self, coffee):
        self._coffee = coffee
    def cost(self):
        return self._coffee.cost() + 2

basic_coffee = Coffee()
coffee_with_milk = MilkDecorator(basic_coffee)
print(coffee_with_milk.cost())  # Outputs 7

Here, MilkDecorator adds the cost of milk to the basic coffee without changing the Coffee class.