Design Patterns: Decorator

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.      
  6. public class Sword : IWeapon    
  7. {    
  8.     public int Damage    
  9.     {    
  10.         get    
  11.         {    
  12.             return 10;    
  13.         }    
  14.     }    
  15. }  

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.      
  6.     public WeaponUpgrade(IWeapon weapon)    
  7.     {    
  8.         this.weapon = weapon;    
  9.     }    
  10.      
  11.     public virtual int Damage    
  12.     {    
  13.         get    
  14.         {    
  15.             return this.weapon.Damage;    
  16.         }    
  17.     }    
  18. }    
  19.      
  20.      
  21. public class SteelSwordDecorator : WeaponUpgrade    
  22. {    
  23.     public SteelSwordDecorator(IWeapon weapon)    
  24.         : base(weapon)    
  25.     {    
  26.      
  27.     }    
  28.      
  29.     // 100 damage from Steel + original weapon damage    
  30.     public override int Damage    
  31.     {    
  32.         get    
  33.         {    
  34.             return 100 + base.Damage;    
  35.         }    
  36.     }    
  37. }  

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.      
  4. // sword.Damage = 110    
  5. sword = new SteelSwordDecorator(sword);    
  6.      
  7. // sword.Damage = 210    
  8. 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.


Similar Articles