我的理解:装饰模式用于拓展类功能,用于补充继承功能。要点一是包装另一个类,要点二是实现一环扣一环的连锁功能执行。
原文解释:动态给一个对象添加额外的职责。就灵活性而言,比子类更灵活。
实例设计了一个不同装扮的功能。例如简介+T恤,或者简介+衬衣。设计图如下:
代码:
class Program
{
public static void Run()
{
Decorator_人 d = new Decorator_人();
d.Name = "小菜";
Decorator_T恤 du1 = new Decorator_T恤();
Decorator_衬衣 du2 = new Decorator_衬衣();
Decorator_牛仔裤 dd1 = new Decorator_牛仔裤();
Decorator_西裤 dd2 = new Decorator_西裤();
Console.WriteLine("第一套装扮:");
du1.SetDecorator(d);
dd1.SetDecorator(du1);
dd1.Show();
Console.WriteLine();
Console.WriteLine("第二套装扮:");
du2.SetDecorator(d);
dd2.SetDecorator(du2);
dd2.Show();
Console.WriteLine();
Console.WriteLine("第三套装扮:");
du1.SetDecorator(d);
dd2.SetDecorator(du1);
dd2.Show();
Console.WriteLine();
Console.WriteLine("》》》相亲失败");
Decorator_运动鞋 df1 = new Decorator_运动鞋();
Decorator_皮鞋 df2 = new Decorator_皮鞋();
Console.WriteLine("第四套装扮:");
du1.SetDecorator(d);
dd2.SetDecorator(du1);
df1.SetDecorator(dd2);
df1.Show();
Console.WriteLine();
Console.WriteLine("》》》相亲失败");
Console.WriteLine("第五套装扮:");
du2.SetDecorator(d);
dd2.SetDecorator(du2);
df2.SetDecorator(dd2);
df2.Show();
Console.WriteLine();
Console.WriteLine("》》》相亲成功");
}
}
abstract class Person
{
protected string _name;
public string Name { get => _name; set => _name = value; }
public virtual void Show()
{
Console.Write(_name + "的装扮是:");
}
}
class Decorator : Person
{
protected Person p;
public void SetDecorator(Person d)
{
this.p = d;
}
public override void Show()
{
//base.Show();
this.p?.Show();
Console.Write(" ");
}
}
class Decorator_人 : Person
{
public override void Show()
{
//base.Show();
简介();
}
private void 简介()
{
Console.Write(base._name + "的装扮:");
}
}
class Decorator_T恤 : Decorator
{
public override void Show()
{
base.Show();
穿T恤();
}
private void 穿T恤()
{
Console.Write("上身:T恤");
}
}
class Decorator_衬衣 : Decorator
{
public override void Show()
{
base.Show();
穿衬衣();
}
private void 穿衬衣()
{
Console.Write("上身:衬衣");
}
}
class Decorator_牛仔裤 : Decorator
{
public override void Show()
{
base.Show();
穿牛仔裤();
}
private void 穿牛仔裤()
{
Console.Write("下身:牛仔裤");
}
}
class Decorator_西裤 : Decorator
{
public override void Show()
{
base.Show();
穿西裤();
}
private void 穿西裤()
{
Console.Write("下身:西裤");
}
}
class Decorator_运动鞋 : Decorator
{
public override void Show()
{
base.Show();
穿运动鞋();
}
private void 穿运动鞋()
{
Console.Write("脚上:运动鞋");
}
}
class Decorator_皮鞋 : Decorator
{
public override void Show()
{
base.Show();
穿皮鞋();
}
private void 穿皮鞋()
{
Console.Write("脚上:皮鞋");
}
}