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.

  1. public interface IWeapon
  2. {
  3. int Damage { get; }
  4. }
  5. public class Sword : IWeapon
  6. {
  7. public int Damage
  8. {
  9. get
  10. {
  11. return 10;
  12. }
  13. }
  14. }

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.

  1. // Decorator
  2. public abstract class WeaponUpgrade : IWeapon
  3. {
  4. protected IWeapon weapon;
  5. public WeaponUpgrade(IWeapon weapon)
  6. {
  7. this.weapon = weapon;
  8. }
  9. public virtual int Damage
  10. {
  11. get
  12. {
  13. return this.weapon.Damage;
  14. }
  15. }
  16. }
  17. public class SteelSwordDecorator : WeaponUpgrade
  18. {
  19. public SteelSwordDecorator(IWeapon weapon)
  20. : base(weapon)
  21. {
  22. }
  23. // 100 damage from Steel + original weapon damage
  24. public override int Damage
  25. {
  26. get
  27. {
  28. return 100 + base.Damage;
  29. }
  30. }
  31. }

To use this structure we just need to instantiate a decorator class and “put on top of” our previous class:

  1. // sword.Damage = 10
  2. IWeapon sword = new Sword();
  3. // sword.Damage = 110
  4. sword = new SteelSwordDecorator(sword);
  5. // sword.Damage = 210
  6. 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.