[X]

C# Decorator Pattern - Design Patterns in Action

 

Decorator Design Pattern

What is Decorator Pattern?

Decorator expands the functionality of an instance of class without changing the class code. It provides a way to attach new state and behavior to an object dynamically. The object does not know it is being decorated. It takes and existing object and adds new functionality to it.
We can take example of a window which can be decorated with a scroll bar if the content displayed on the window is gets over-flowed. Also we can think example of decorating an existing image with border/watermark at runtime. So we can see that the beauty of this pattern is:

  • The original object is unaware of decoration.
  • Now we don't need to create one big class full of all the features, rather we can decorate the object at runtime mixing the decorations to them.


So what are the various essential players to the decorator pattern?

Component:

Original class(es) which are going to be expanded by adding new features to them.

Operation:

An interface IComponent, which contains the operations which can be replaced.

Decorator:

A class which implements/inherits from IComponent and adds state and/or behaviour to the Component.

Decorator pattern has 2 kind of relationship:

Is-a

Decorator inherits of IComponent and can be used in place of IComponent by client.

Has-a

Decorator instantiates one or more IComponent objects, decorates them and they can be replace the original IComponent objects.
More...

Posts By Month