装饰模式是在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。
public class Person
{
public string Name { get; set; }
public Person() { }
public Person(string name)
{
Name = name;
}
public virtual void Show()
{
Console.WriteLine(string.Format("装扮的{0}", Name));
}
}
public class Finery : Person
{
protected Person component;
public void Decorate(Person com)
{
component = com;
}
public override void Show()
{
if (component != null)
{
component.Show();
}
}
}
public class Suit : Finery
{
public override void Show()
{
Console.WriteLine("穿西装");
base.Show();
}
}
public class Tie : Finery
{
public override void Show()
{
Console.WriteLine("打领带");
base.Show();
}
}
public class TShirts : Finery
{
public override void Show()
{
Console.WriteLine("大 T 恤");
base.Show();
}
}
使用装饰器的代码:
Person per = new Person("mao");
Console.WriteLine("第一种装扮:");
TShirts ts = new TShirts();
Suit su = new Suit();
Tie tie = new Tie();
su.Decorate(per);
tie.Decorate(su);
ts.Decorate(tie);
ts.Show();
未使用装饰器的代码:
Person perB = new Person("Mao");
Console.WriteLine("第二种装扮:");
TShirts tsB = new TShirts();
Suit suB = new Suit();
Tie tieB = new Tie();
tsB.Show();
tieB.Show();
suB.Show();
perB.Show();
不仅要看懂设计模式,还要知道在什么场景下用。
比如装饰模式和策略模式的区别,装饰模式可以勉强的理解为按顺序组装多种策略在一起,而策略模式就是选择某一种策略并只暴露选择策略的接口隐藏策略的实现算法。
第 2 个实现方式:
// 形状
public abstract class Shape
{
public abstract void Draw();
}
// 圆形
public class Circle : Shape
{
public override void Draw()
{
Console.WriteLine("Draw Circle");
}
}
// 方形
public class Rectangle : Shape
{
public override void Draw()
{
Console.WriteLine("Draw Rectangle");
}
}
// 形状装饰器
public class ShapeDecorator : Shape
{
protected Shape decoratedShape;
public void SetDecorate(Shape sh)
{
decoratedShape = sh;
}
public override void Draw()
{
decoratedShape.Draw();
}
}
// 红色的形状装饰器
public class RedShapeDecorator : ShapeDecorator
{
public override void Draw()
{
base.Draw();
Console.WriteLine("Draw Red");
}
}
// 黄色的形状装饰器
public class YellowShapeDecorator : ShapeDecorator
{
public override void Draw()
{
base.Draw();
Console.WriteLine("Draw Yellow");
}
}
//业务运用
Console.WriteLine("");
Console.WriteLine("第 1 种形状:黄圆");
YellowShapeDecorator ys = new YellowShapeDecorator();
ys.SetDecorate(new Circle());
ys.Draw();
Console.WriteLine("");
Console.WriteLine("第 2 种形状:红方形");
RedShapeDecorator rs = new RedShapeDecorator();
rs.SetDecorate(new Rectangle());
rs.Draw();
Console.WriteLine("");
Console.WriteLine("第 3 种形状:黄红方形");
RedShapeDecorator rs2 = new RedShapeDecorator();
rs2.SetDecorate(new Rectangle());
YellowShapeDecorator ys2 = new YellowShapeDecorator();
ys2.SetDecorate(rs2);
ys2.Draw();
输出:
第 1 种形状:黄圆
Draw Circle
Draw Yellow
第 2 种形状:红方形
Draw Rectangle
Draw Red
第 3 种形状:黄红方形
Draw Rectangle
Draw Red
Draw Yellow