前言
裝飾者模式也是在編碼設計中使用非常頻繁的設計模式之一,尤其是在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();
}
}
結語
本篇只是介紹裝飾者模式,不具備權威性,代碼也只是作為演示使用,具體的使用還是仁者見仁智者見智,看具體場景而發揮。其實從接口的間接調用來說,裝飾者模式有點像適配器模式又有點像是代理模式,這里面的聯系和區別以后可以展開討論


