尊重时间 时间才会尊重你。
「1」说明
此乃《设计模式》之装饰模式
「2」装饰模式定义
动态地给一个对象添加一些额外的指责,就增加功能来说,装饰模式比生成子类更为灵活。
「3」装饰(Decotator)模式结构图
- Conponent:定义一个对象接口,可以给这些对象动态地添加职责。
- ConcreteComponent:定义一个具体的对象,也可以给这个对象添加一些职责。
- Decorator:装饰抽象类,继承了Component,从外类来扩展Component类的功能,但是对于Component来说,是无需知道Decorator的存在的。
- ConreteDecorator:具体的装饰对象,给Component添加功能。
「4」什么时候使用装饰及模式和它好处
- 装饰模式是为已有功能动态地添加更多功能的一种方式。当系统需要新功能的时候,是向旧的类中添加新的代码。这些新加的代码通常装饰了原有类的核心职责和主要行为。它们在主类中加入了新的字段,新的方法和新的逻辑,从而增加了主类的复杂度,而这些新加入的东西仅仅是为了满足一些只在特定情况下才会执行的特殊行为的需要。而装饰模式却提供了一个非常好的解决方案,它把每个要装饰的功能放在单独的类中,并让这个类包装它所要装饰的对象,因此,当需要执行特殊行为时,客户代码就可以在运行时根据需要有选择地、按顺序地使用装饰功能包装对象了。
- 优点就是把类中的装饰功能从类中搬移去除,有效地把类中的核心职责和装饰功能区分开,这样可以简化相关类中重复的装饰逻辑。
「5」装饰模式基本代码推演
- Component类
abstract class Component
{
public abstract void Operation();
}
- ConcreteComponent类
class ConcreteComponent : Component
{
public override void Operation()
{
Console.WriteLine("具体对象的操作");
}
}
- Decorator类
abstract class Decorator : Component
{
protected Component component;
public void SetComponent(Component conponent)
{
this.component = component;
}
public override void Operation()
{
if(component != NULL)
{
component.Operation();
}
}
}
ConcreteDecorator类
class ConcreteDecoratorA : Decorator
{
private string addedState;
public override void Operation()
{
base.Opetation();
addedState = "New State";
Console.WriteLine("具体装饰对象A的操作");
}
}
class ConcreteDecoratorB : Decorator
{
public override void Operation()
{
base.Opetation();
AddedBehavior;
Console.WriteLine("具体装饰对B的操作");
}
private void AddedBehavior()
{
}
}
- 客户端代码
static void Main()
{
ConcreteComponent c = new ConcreteComponent();
ConcreteDecoratorA d1 = new ConcreteDecoratorA;
ConcreteDecoratorB d2 = new ConcreteDecoratorB;
d1.SetComponent(c);
d2.SetComponent(d1);
Console.Read();
}
「6」装饰模式总结
装饰模式把类中的装饰功能从类中搬移去除,有效地把类中的核心职责和装饰功能区分开,这样可以简化相关类中重复的装饰逻辑。