Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>As others have already said Decorators are good for adding "options" to things... The benefits come in the way you can chain methods etc. through the decorators.</p> <p>Imagine I buy a car with options for leather interior, metallic paint and awesome spoiler... </p> <p>There are 8 different combinations of the three options but with decorators you only need three extra classes.</p> <p>The interesting thing though is the way the decorator pattern works. As a brief example:</p> <pre><code>public class MetallicPaint : Car { private Car car; public MetallicPaint(Car wrappedCar) { car = wrappedCar; } public decimal Cost() { return car.Cost() + 500; } public string Description() { return car.Description() + ", Metallic Paint"; } public string Speed() { return car.Speed(); } [... {pass through other methods and properties to the car object}] } </code></pre> <p>This isn't a complete example but highlights how the decorator can interact with the object it is decorating. And of course because it implements car it can be used just like a car in every other way (and passes through anything the decorator doesn't effect to the inner car object).</p> <p>Of course if you had multiple of these decorators with a car nested inside each would in turn add their cost, their part of the description and maybe the spoiler would alter the speed whereas the others didn't...</p> <p>In essence it allows you to modify an object in a much more modular and less fundamental way than inheritance would. Decorators should always be used as if they were the base object (in this case <code>Car</code>) so they should never expose any new methods or properties, just slightly change the effect of existing ones.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload