前言
装饰器模式可以在运行时为对象添加额外的功,而无需修改原始对象的代码。这种方式比继承更加灵活。
代码
//蛋糕类(抽象类)
public abstract class Cake
{
public abstract void Create();
}
//奶油蛋糕类
public class CreamCake : Cake
{
public override void Create()
{
Console.WriteLine("制作奶油蛋糕...");
}
}
//蛋糕装饰器类(抽象类)
public abstract class CakeDecorator : Cake
{
protected Cake cake;
protected CakeDecorator(Cake cake)
{
this.cake = cake;
}
public override void Create()
{
cake.Create();
}
}
//草莓装饰器类
public class StrawberryDecorator : CakeDecorator
{
public StrawberryDecorator(Cake cake) : base(cake){}
public override void Create()
{
base.Create();
AddDecorator();
}
public void AddDecorator()
{
Console.WriteLine("给蛋糕添加草莓..");
}
}
//芒果装饰器类
public class MangoDecorator : CakeDecorator
{
public MangoDecorator(Cake cake) : base(cake)
{
}
public override void Create()
{
base.Create();
AddDecorator();
}
public void AddDecorator()
{
Console.WriteLine("给蛋糕添加芒果..");
}
}
/*
* 结构模型:Structural Pattern
* 装饰器模式:Decorator Pattern
*/
internal class Program
{
static void Main(string[] args)
{
//制作奶油蛋糕
Cake creamCake = new CreamCake();
//给奶油蛋糕 + 草莓=>草莓奶油蛋糕
CakeDecorator strawberryDecorator = new StrawberryDecorator(creamCake);
//给草莓奶油蛋糕 + 芒果 => 草莓奶油 芒果 蛋糕
CakeDecorator mangoDecorator = new MangoDecorator(strawberryDecorator);
//制作完成
mangoDecorator.Create();
Console.ReadLine();
}
}