Decorator模式结构图
Food.cs//抽象基类(Componet)
abstract public class Food
{
public string foodName;
public double price;
virtual public string GetName() { return foodName; }
abstract public double GetCost();
}
Decorator.cs//装饰者类(Decorator)
abstract public class Decorator : Food
{
}
Marmite.cs//被装饰的类(ConcreteComponet1)
public class Marmite : Food//砂锅
{
public Marmite()
{
this.foodName = "marmite";
this.price = 4.0;
}
public override string GetName()
{
return this.foodName;
}
public override double GetCost()
{
return price;
}
}
Rice.cs//被装饰的类(ConcreteComponet2)
public class Rice : Food//米饭
{
public Rice()
{
this.foodName = "rice";
this.price = 1.0;
}
public override string GetName()
{
return this.foodName;
}
public override double GetCost()
{
return price;
}
}
Rib.cs//具体装饰者(ConcreteDecoratorA)
public class Rib : Decorator//小排
{
Food food;
public Rib(Food food)
{
this.food = food;
this.foodName = "rib";
this.price = 5.0;
}
public override string GetName()
{
return food.GetName() + "," + foodName;
}
public override double GetCost()
{
return food.GetCost() + price;
}
}
Ham.cs//具体装饰者(ConcreteDecoratorB)
public class Ham : Decorator
{
Food food;
public Ham(Food food)//火腿
{
this.food = food;
this.price = 2.0;
this.foodName = "ham";
}
override public string GetName()
{
return food.GetName() + "," + foodName;
}
public override double GetCost()
{
return food.GetCost() + price;
}
}
Test:
static void Main(string[] args)
{
Rice rice = new Rice();
Ham ham = new Ham(rice);
Rib rib = new Rib(ham);
Console.WriteLine("菜单: {0}", rib.GetName());
Console.WriteLine("总价: {0}", rib.GetCost());
}