The decorator pattern allows behavior to be added to an individual object.
Example c#
public abstract class BaseSalad { protected double myPrice; public virtual double GetPrice() { return this.myPrice; } } public abstract class ExtrasDecorator : BaseSalad { protected BaseSalad salad; public ExtrasDecorator(BaseSalad saladToDecorate) { this.salad = saladToDecorate; } public override double GetPrice() { return (this.pizza.GetPrice() + this.myPrice); } } class Program { static void Main() { GreenSalad salad = new GreenSalad(); Console.WriteLine("Plain GreenSalad: " + salad.GetPrice().ToString()); ExtraCucumbers moreCucumbers = new ExtraCucumbers(salad); ExtraCucumbers someMoreCucumbers = new ExtraCucumbers(moreCucumbers); Console.WriteLine("Plain Green Salad with double extra cucumbers: " + someMoreCucumbers.GetPrice().ToString()); ExtraTomatoes extraTomatoes = new ExtraTomatoes(someMoreCucumbers); Console.WriteLine("Plain GreenSalad with double extra cucumbers with tomatoes: " + extraTomatoes.GetPrice().ToString()); } } public class GreenSalad: BaseSalad { public GreenSalad() { this.myPrice = 3.75; } } public class ExtraCucumbers : ExtrasDecorator { public ExtraCucumbers(BaseSalad saladToDecorate) : base(saladToDecorate) { this.myPrice = 1.30; } } public class ExtraTomatoes : ExtrasDecorator { public ExtraTomatoes(BaseSalad saladToDecorate) : base(saladToDecorate) { this.myPrice = 1.62; } }
Comments are closed, but trackbacks and pingbacks are open.