我们通常可以使用继承来实现功能的拓展,如果这些需要拓展的功能的种类很繁多,那么势必生成很多子类,增加系统的复杂性,同时,使用继承实现功能拓展,我们必须可预见这些拓展功能,这些功能是编译时就确定了,是静态的。
动态地给一个对象添加一些额外的职责。就增加功能来说,Decorator模式相比生成子类更为灵活。
(一)代码
public abstract class Component
{
public abstract void Do1();
public abstract void Do2();
}
public class ConcreteComponent : Component
{
public override void Do1()
{
Console.WriteLine("第一件事。");
}
public override void Do2()
{
Console.WriteLine("第二件事。");
}
}
public abstract class Decorator : Component
{
Component _component;
public Decorator(Component component)
{
_component = component;
}
public override void Do1()
{
_component.Do1();
}
public override void Do2()
{
_component.Do2();
}
}
public class ConcreteDecorator1 : Decorator
{
public ConcreteDecorator1(Component component):base(component)
{
}
public override void Do1()
{
base.Do1();
Console.WriteLine("听着音乐!");
}
}
public class ConcreteDecorator2: Decorator
{
public ConcreteDecorator2(Component component)
: base(component)
{
}
public override void Do2()
{
base.Do1();
Console.WriteLine("吃着零食!");
}
}
(二)测试
[Test]
public void TestDecorator()
{
Component c1 = new ConcreteComponent();
Decorator.Decorator d = new ConcreteDecorator1(c1);
d.Do1();
}
结果:
第一件事。听着音乐!