前言
装饰者模式也是在编码设计中使用非常频繁的设计模式之一,尤其是在AOP等应用上尤其突出。今天就重新回顾一下装饰者模式
UML类图
模式说明
装饰者模式,在不改变原类文件和使用继承的情况下,动态扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。装饰者模式具备以下特点:
- 装饰对象和真实对象具有相同的接口。这样客户端对象就能以和真实对象相同的方式和装饰对象交互
- 装饰对象包含一个真实对象的引用(reference)
- 装饰对象接受所有来自客户端的请求。它把这些请求转发给真实的对象
设计原则
- 多用组合,少用继承
- 类应该设计的对扩展开放,对修改关闭
代码
抽象真实对象
public interface IComponent
{
void Operation();
}
具体真实对象
public class Component : IComponent
{
public void Operation()
{
Console.WriteLine("Component Operation");
}
}
抽象装饰者
public abstract class Decorator : IComponent
{
protected IComponent realComponent;
public Decorator(IComponent component)
{
realComponent = component;
}
public virtual void Operation()
{
if (realComponent != null)
realComponent.Operation();
}
}
日志装饰者
public class LogDecorator : Decorator
{
public LogDecorator(IComponent component)
: base(component)
{
}
public override void Operation()
{
Console.WriteLine("Operation Logging");
base.Operation();
Console.WriteLine("Operation Log Finished");
}
}
授权装饰者
public class AuthDecorator : Decorator
{
public AuthDecorator(IComponent component)
: base(component)
{
}
public override void Operation()
{
Console.WriteLine("Befor Operation Authorization");
base.Operation();
Console.WriteLine("After Operation Authorization");
}
}
测试代码
class Program
{
static void Main(string[] args)
{
IComponent component =
new AuthDecorator(
new LogDecorator(
new Component()
));
component.Operation();
Console.ReadLine();
}
}
结语
本篇只是介绍装饰者模式,不具备权威性,代码也只是作为演示使用,具体的使用还是仁者见仁智者见智,看具体场景而发挥。其实从接口的间接调用来说,装饰者模式有点像适配器模式又有点像是代理模式,这里面的联系和区别以后可以展开讨论

