一 概要
1.1 结构型模式
关注类和对象的组合。继承的概念被用来组合接口和定义组合对象,从而获得新功能。
1.2 定义
指在不改变现有对象结构的情况下,动态地给该对象增加一些额外的职责。
二 UML类图
三 例子
public interface Component
{
void Operation ( ) ;
}
public class ConcreteComponent : Component
{
public void Operation ( )
{
}
}
public abstract class Decorator : Component
{
private Component component;
public void SetComponent ( Component component)
{
this . component = component;
}
public virtual void Operation ( )
{
if ( this . component != null )
{
this . component. Operation ( ) ;
}
}
}
public class DecoratorA : Decorator
{
private string state;
public override void Operation ( )
{
base. Operation ( ) ;
state = "todo" ;
}
}
public class DecoratorB : Decorator
{
public override void Operation ( )
{
base. Operation ( ) ;
Other ( ) ;
}
private void Other ( )
{
}
}
public Test ( )
{
ConcreteComponent concreteComponent = new ConcreteComponent ( ) ;
DecoratorA decoratorA = new DecoratorA ( ) ;
DecoratorB decoratorB = new DecoratorB ( ) ;
decoratorA. SetComponent ( concreteComponent) ;
decoratorB. SetComponent ( decoratorA) ;
decoratorB. Operation ( ) ;
}
四 优缺点
4.1 优点
把类中的装饰功能从类中搬移去除,简化了原有的类。 有效地把类的核心职责和装饰功能区分开来,而且可以去除相关类中重复的装饰逻辑。 比继承更加灵活机动。
4.2 缺点
这种比继承更加灵活机动的特性,也同时意味着更加多的复杂性。 装饰模式会导致设计中出现许多小类,如果过度使用,会使程序变得很复杂。
五 使用场景
装饰模式是为已有功能动态地添加更多功能的一种方式。当系统需要新功能, 而向旧的类中添加新的代码是为了装饰原有类的核心职责或主要行为时,而且向旧的类中添加新的方法和逻辑只会在某些特定的情况下才会用到, 这个时候就可以使用装饰模式, 把装饰的代码放在单独的类中,并让这个类包装它需要装饰的对象。