The Decorator Pattern in C#

by David Kiff 18. December 2008 13:09

This small article aims to explain what the decorator pattern is and how it could be applied in C#.

One of the Object Orientated principles is “open for extension and closed for modification”. The Decorator pattern stays true to this principle because it allows you to add extra functionality to existing objects without making any code changes.

The Decorator pattern uses composition to wrap an existing object giving it additional responsibilities, rather than using inheritance to extend functionality. There are several disadvantages to using inheritance over Decorators to achieve this:

  1. The inheritance hierarchy will start to become very complex when there are many derived classes, making debugging and maintenance harder.
  2. The inheritance hierarchy will enforce certain rules, meaning it will be harder to mix and match different options resulting in reduced flexibility.
  3. Derived classes will have an ever lasting longer name, for example, adding alloy wheels, car mats and Metallic paint to a car could result in a class name of StandardCarWithAlloyWheelsMatsAndPaints.

The Decorator class must implement the same interface as the component they are going to decorate so they can be used interchangeably.

It is important to note that this is an example of the design pattern and should be used where appropriate!

The code sample provided demonstrates decorating a standard car with additional accessories such as alloy wheels and mats.

Decorator UML

 Download Code

 

Tags:

Patterns

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading