The following is a sample of the Decorator Design Pattern in action taken from the Head First Series.
Example:
In this example the Beverage is a closed Object so we can't change it.
So by creating the CondimentDecorator abstract class that inherits from Beverage we can add or override certain behaviour of Beverage.
Whip is a CondimentDecorator but it is also Beverage. As we add CondimentDecorator types around Beverage the cost of the Beverage is accumulating.
We are extending the behaviour.
Every time we create a new CondimentDecorator object and pass the Beverage reference to the constructor we are extending behaviour to Beverage.
Code Snippet...
namespace Martins.Decorator.Pattern
{
class StarbuzzCoffee
{
static void Main(string[] args)
{
//Decorate Espresso with Mocha and Whip
Beverage beverage2 = new Espresso();
beverage2 = new Mocha(beverage2);
beverage2 = new Whip(beverage2);
//Decorate HouseBlend with Soy, Mocha and Whip
Beverage beverage3 = new HouseBlend();
beverage3 = new Soy(beverage3);
beverage3 = new Mocha(beverage3);
beverage3 = new Whip(beverage3);
}
}
public abstract class Beverage
{
string description = "Unknown Beverage";
public virtual string Description
{
get
{
return description;
}
set
{
description = value;
}
}
public abstract double Cost
{
get;
}
}
public class Espresso : Beverage
{
public Espresso()
{
Description = "Espresso";
}
public override double Cost
{
get
{
return 1.99;
}
}
}
public class HouseBlend : Beverage
{
public HouseBlend()
{
Description = "House Blend Coffee";
}
public override double Cost
{
get
{
return .89;
}
}
}
public abstract class CondimentDecorator : Beverage
{
}
public class Whip : CondimentDecorator
{
Beverage beverage;
public Whip(Beverage beverage)
{
this.beverage = beverage;
}
public override string Description
{
get
{
return beverage.Description + ", Whip";
}
set
{
this.Description = value;
}
}
public override double Cost
{
get
{
return .10 + beverage.Cost;
}
}
}
public class Mocha : CondimentDecorator
{
Beverage beverage;
public Mocha(Beverage beverage)
{
this.beverage = beverage;
}
public override string Description
{
get
{
return beverage.Description + ", Mocha";
}
}
public override double Cost
{
get
{
return .20 + beverage.Cost;
}
}
}
public class Soy : CondimentDecorator
{
Beverage beverage;
public Soy(Beverage beverage)
{
this.beverage = beverage;
}
public override string Description
{
get
{
return beverage.Description + ", Soy";
}
}
public override double Cost
{
get
{
return .15 + beverage.Cost;
}
}
}
}


No comments:
Post a Comment