设计模式之笔记--装饰模式(Decorator)
装饰模式(Decorator)
定义
装饰模式(Decorator),动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。
类图
描述
Component:被装饰者和装饰者共有的基类;
ConcreteComponent:被装饰者的具体类;
Decorator:装饰类,包含一个Component实例;
ConcreteDecorator:具体的装饰类,其构造函数里有一个Component实例,方法可以扩展。
应用场景
下面条的时候,可以在面条里放入西红柿、鸡蛋等食材,如果只在面条里放入西红柿,就是西红柿面条;如果只在面条里放入鸡蛋,就是鸡蛋面条;如果在面条里放入西红柿和鸡蛋,就是西红柿鸡蛋面条。面条可以看作被装饰者,西红柿、鸡蛋则可以被看作装饰者。
/// <summary> /// 食物 /// </summary> public abstract class Food { private string name; /// <summary> /// 食物的名称 /// </summary> public string Name { get { return name; } set { name = value; } } public abstract void Cook(); } /// <summary> /// 面条 /// </summary> public class Noodles : Food { public Noodles() { this.Name = "面条"; } public override void Cook() { Console.WriteLine(this.Name); } } /// <summary> /// 食材 /// </summary> public abstract class Ingredients : Food { protected Food food; public Ingredients(Food food) { this.food = food; } } /// <summary> /// 西红柿 /// </summary> public class Tomato : Ingredients { public Tomato(Food food) : base(food) { this.Name = "西红柿" + this.food.Name; } public override void Cook() { Console.WriteLine(this.Name); } } /// <summary> /// 鸡蛋 /// </summary> public class Egg : Ingredients { public Egg(Food food) : base(food) { this.Name = "鸡蛋" + this.food.Name; } public override void Cook() { Console.WriteLine(this.Name); } }