案例转自https://www.cnblogs.com/stonefeng/p/5679638.html
//主体基类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DecoratorModeDemo
{
abstract class PanCake
{
public string desc = "";
public abstract string getDesc();
public abstract double price();
}
}
//主体:肉夹馍
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DecoratorModeDemo
{
class Roujiamo:PanCake
{
public Roujiamo()
{ this.desc = "肉夹馍"; }
public override string getDesc()
{
return desc;
}
public override double price()
{
return 6;
}
}
}
//主体手抓饼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DecoratorModeDemo
{
class TornCake:PanCake
{
public TornCake()
{
this.desc = "手抓饼";
}
public override string getDesc()
{
return desc;
}
public override double price()
{
return 4;
}
}
}
//装饰者基类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DecoratorModeDemo
{
abstract class Condiment:PanCake
{
public PanCake panCake;
public Condiment(PanCake p)
{
panCake = p;
}
}
}
//装饰者煎蛋
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DecoratorModeDemo
{
class FiredEgg:Condiment
{
public FiredEgg(PanCake pancake):base(pancake)
{
}
public override string getDesc()
{
return panCake.getDesc()+",煎蛋";
}
public override double price()
{
return this.panCake.price() + 2;
}
}
}
//主函数
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DecoratorModeDemo
{
class Program
{
static void Main(string[] args)
{
TornCake torncake = new TornCake();
Console.WriteLine(torncake.getDesc() + " ¥" +torncake.price().ToString());
PanCake roujiamo = new Roujiamo();
roujiamo = new FiredEgg(roujiamo);
roujiamo = new FiredEgg(roujiamo);
Console.WriteLine(roujiamo.getDesc()+" ¥"+roujiamo.price());
Console.ReadLine();
}
}
}
运行结果
心得:装饰者派生自主体基类,继承了主体需要操作的对象。同时装饰者的成员对象中有主体,用以耦合主体。通过创建不同的装饰者派生类,重写主体类方法来实现对主体类的不同操作。
roujiamo = new FiredEgg(roujiamo)实际上roujiamo已经变成了煎蛋,只不过这个煎蛋的成员包含肉夹馍,返回的方法经重写已经用原肉夹馍处理过了。