In C#, the decorator pattern is a structural design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class. This pattern is very useful when you want to enhance the functionality of an object without changing its original implementation.
To use the decorator pattern in C#, we need to create a base abstract class, which will define the basic functionality of the objects that we want to enhance. Then we create a concrete implementation of this base class and add behaviors to it using one or more decorators.
Here is an example of a simple implementation of the decorator pattern in C#:
main.cs1180 chars59 lines
In this example, we first define the base abstract class Shape
, which provides the basic functionality of computing the area of a shape. We then implement a concrete class Circle
that derives from Shape
and provides implementation for its Area()
method.
Next, we define an abstract decorator ColorDecorator
that also derives from Shape
. This decorator takes a Shape
object as input and adds functionality to the object. In this case, the added functionality is the ability to provide the color of the object. We then create a concrete decorator RedColorDecorator
that derives from ColorDecorator
, and adds the Color()
method that returns the color of the object as "Red".
Finally, we demonstrate how to use the decorator pattern by creating an instance of the Circle
class and then wrapping it in a RedColorDecorator
. This produces a new object that has the added functionality of providing the color of the object.
gistlibby LogSnag