The Decorator Design Pattern is a structural pattern that allows behavior to be added to individual objects, dynamically, without affecting the behavior of other objects from the same class. It's a flexible alternative to subclassing for extending functionality.
Here's an example of how you can implement the Decorator Design Pattern in C#:
Component Interface (IComponent): This interface defines the Operation
method that all components and decorators must implement.
Concrete Component: This is the class that we want to add new behavior to. It implements the IComponent
interface.
Base Decorator (Decorator): This abstract class implements the IComponent
interface and has a reference to an IComponent
object. The base decorator delegates the Operation
method to the wrapped component.
Concrete Decorators (ConcreteDecoratorA, ConcreteDecoratorB): These classes extend the base decorator and add their own behavior before or after calling the base decorator's Operation
method.
Client Code: The client creates a ConcreteComponent
object and wraps it with ConcreteDecoratorA
and ConcreteDecoratorB
. The final call to Operation
executes all the operations in the order of wrapping.
The Decorator Design Pattern is useful when you need to add responsibilities to objects dynamically and independently without affecting other objects.