Decorator Design Pattern

If you want to add new functionality to your object without change the structure of your object, you can use Decorator Design Pattern.

I try to explain the usage of Decorator Design Pattern in the example below.

Scenario

Imagine that, there is an Attack Object. The Attack object has a method named SetDamage(). In this example, we are going to create two objects, Punch and HighKick. Punch and HighKick objects derived from Attack Object. The main purpose of the scenario is adding poison to any object derived from Attack Object.

Step 1

We are creating our Attack Base Class and derive two class (Punch and HighKick) from the Attack Object.

Attack.cs

Punch.cs

HighKick.cs

Step 2 

In this step, we are going to create an Attack Decorator. The decorater has reference of an Attack Object. Why we keep a reference of an Attack object in our decorator? Because the decorator object can add new functionality to the Attack object in this way without changing the structure of the Attack class.

AttackDecorator.cs

Step 3

Let’s derive PoisonAttackDecorator from AttackDecorator. PoisonAttackDecorator adds poison functionality to any Attack Object.

PoisonAttackDecorator.cs

Step 4

DecoratorDesignDemo.cs

Output

 

Feel free to contact me directly at cosgun.halil@gmail.com.

Have a nice day.