装饰模式Decorator是动态的给对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更加灵活。
component类
namespace Decorator
{
abstract class Component
{
public abstract void Operation();
}
}
concretecomponent类
namespace Decorator
{
class ConcreteComponent : Component
{
public override void Operation()
{
Console.WriteLine("具体对象的操作");
}
}
}
decorator类
namespace Decorator
{
abstract class Decorator: Component
{
protected Component component;
/// <summary>
/// 设置component
/// </summary>
/// <param name="component"></param>
public void SetComponent (Component component)
{
this.component = component;
}
/// <summary>
/// 重写operation,实际执行的是component的 Operation
/// </summary>
public override void Operation()
{
if (component != null)
{
component.Operation();
}
}
}
}
ConcreatDecoratorA类
namespace Decorator
{
class ConcreatDecoratorA: Decorator
{
/// <summary>
/// 本类的独有功能,以区别于ConcreatDecoratorB
/// </summary>
private string addedState;
/// <summary>
/// 首先运行Component的operation
/// 再执行本类的功能,如 addedState(),相当于对Component进行了装饰
/// </summary>
public override void Operation()
{
base.Operation();
addedState = "New State";
Console.WriteLine("具体的操作对象A的操作");
}
}
}
ConcreatDecoratorB类
namespace Decorator
{
class ConcreatDecoratorB : Decorator
{
/// <summary>
/// 首先运行Component的operation
/// 再执行本类的功能,如AddedBehavior(),相当于对Component进行了装饰
/// </summary>
public override void Operation()
{
base.Operation();
AddedBehavior();
Console.WriteLine("具体装饰对象B的操作");
}
/// <summary>
/// 本类的独有方法,以区别于ConcreatDecoratorB
/// </summary>
private void AddedBehavior()
{
}
}
}
客户端代码
namespace Decorator
{
class Program
{
static void Main(string[] args)
{
/*装饰的方法是:
首先先用ConcreteComponent实例化对象C
然后用ConcreatDecoratorA的实例化对象d1来包装c
再用ConcreatDecoratorB的实例化对象d2来包装d1
最终执行d2的Operation
*/
ConcreteComponent c = new ConcreteComponent();
ConcreatDecoratorA d1 = new ConcreatDecoratorA();
ConcreatDecoratorB d2 = new ConcreatDecoratorB();
d1.SetComponent(c);
d2.SetComponent(d1);
d2.Operation();
Console.ReadKey();
}
}
}
装饰模式是为已有功能动态地添加更多功能的一种方式。但到底什么时候用它呢?
你起初的设计中,当系统需要新功能的时候,是向旧的类中添加新的代码。这些新加的代码通常装饰了原有类的核心职责或主要行为,比如用西装或嘻哈服来装饰小菜,但这种做法的问题在子,已们在主类中加入了新的宇段,新的方法和新的逻辑,从而增加了主类的复杂度,就像你起初的那个 ‘人’类,而这些新加入的东西仅仅是为了满足一些只在某种特定情况下才会执行的特殊行为的需要。而装饰模式却提供了一个非常好的解决方案,它把每个要装饰的功能放在单独的类中,并让这个类包装它所要装饰的对象,因此,当需要执行特殊行为时,客户代码就可以在运行时根据需要有选择地、按顺序地使用装饰功能包装对象了【DDP】。所以就出现了上面那个例子的情况,我可以通过装饰,让你全副武装到牙齿,也可以让你只挂一丝到内裤。
饰模式的优点我总结下来就是,把类中的装饰功能从类中搬移去除,这样可以简化原有的类。
这样做更大的好处就是有效地把类的核心职责和装饰功能区分开了。而且可以去除相关类中重复的装饰逻辑。
需要原码请私信