装饰模式学习
装饰模式是利用SetComponent来对对象进行包装。这样每个装饰的对象实现和如何使用这个对象分离开了,每个装饰对象之关心自己的功能,不需要关心如何被添加到对象链当中。
一下以一个组件足球明星队的过程,来说明装饰模式
1.(Team)类(ConcreteComponent) 被装饰的球队
class Team
{
public Team()
{ }
private string name;
public Team(string name)
{
this.name = name;
}
public virtual void Show()
{
Console.WriteLine("组成了:{0}", name);
}
}
2.(Builder)类(Decorator)类 组件球队
class Builder:Team
{
protected Team component;
public void Decorate(Team component)
{
this.component = component;
}
public override void Show()
{
if (component != null)
{
component.Show();
}
}
}
3.(ConcreteDecorator)类 具体球员
class Henry:Builder
{
public override void Show()
{
Console.Write("亨利 ");
base.Show();
}
}
class Ronaldo : Builder
{
public override void Show()
{
Console.Write("罗纳尔多 ");
base.Show();
}
}
class Figo : Builder
{
public override void Show()
{
Console.Write("菲戈 ");
base.Show();
}
}
4.(Program)类 (测试)
class Program
{
static void Main(string[] args)
{
Team t = new Team("明星队");
Console.WriteLine("\n组建球队");
Henry h = new Henry();
Ronaldo r = new Ronaldo();
Figo f = new Figo();
//为球队添加球员,比作装饰的过程
h.Decorate(t);
r.Decorate(h);
f.Decorate(r);
f.Show();
Console.Read();
}
}
总结:装饰模式是为已有的功能动态的功能的一种方式,上面例子用到的是一个以组建足球队的形式来模拟这种模式,你可以这样认为;原先的球队里已经有足够的球员,为了增添球队的实力,需要签入更多的大牌球星,这个过程好比装饰的过程,在原有的基础上,添加额外的东西。
浙公网安备 33010602011771号