Decorator Pattern: Definition and Core Problem
In object-oriented design, you often need to add functionalities to objects at runtime. Traditional approaches create issues: First, using inheritance for every combination leads to a class explosion (if you have 3 features, you need 2^3 = 8 subclasses). Second, inheritance is static and decided at compile time, not runtime. Third, modifying the base class affects all subclasses violating the Open/Closed Principle (OCP).
Key Characteristics:
First, decorators implement the same interface as the objects they wrap, making them interchangeable. Second, decorators contain a reference to the wrapped object (composition over inheritance). Third, decorators forward requests to the wrapped object and may perform additional actions before or after forwarding. Fourth, multiple decorators can be stacked, creating a chain of responsibility.
When NOT to Use: If you only have one or two variations, simple inheritance is cleaner. If the order of decorators matters significantly and creates complex dependencies, consider the Strategy Pattern instead. If you need to remove decorators dynamically after adding them, this pattern becomes cumbersome.