The Decorator Design Patterns is handy for adding behavior or state to an object during runtime.
If we are developing a game it could be used to handle item upgrades. In the following example there is a simple Sword. From this simple item we can upgrade it and add more damage to it.
- public interface IWeapon
- {
- int Damage { get; }
- }
-
- public class Sword : IWeapon
- {
- public int Damage
- {
- get
- {
- return 10;
- }
- }
- }
We now have a simple Sword. To add the decorator pattern we need to create the upgrades. The decorator class will take the weapon and increment its values.
-
- public abstract class WeaponUpgrade : IWeapon
- {
- protected IWeapon weapon;
-
- public WeaponUpgrade(IWeapon weapon)
- {
- this.weapon = weapon;
- }
-
- public virtual int Damage
- {
- get
- {
- return this.weapon.Damage;
- }
- }
- }
-
-
- public class SteelSwordDecorator : WeaponUpgrade
- {
- public SteelSwordDecorator(IWeapon weapon)
- : base(weapon)
- {
-
- }
-
-
- public override int Damage
- {
- get
- {
- return 100 + base.Damage;
- }
- }
- }
To use this structure we just need to instantiate a decorator class and “put on top of” our previous class:
-
- IWeapon sword = new Sword();
-
-
- sword = new SteelSwordDecorator(sword);
-
-
- sword = new SteelSwordDecorator(sword);
We of course could have multiple types of decorators (Diamond Sword, Flame Sword and so on).
One example in Starcraft is the weapon upgrades, John Lindquist explains about it in a Pattern Craft video: PatternCraft - Decorator Pattern.