裝飾模式是一種用於代替繼承的技術,達到無需定義子類卻能夠給對象動態增長職責的效果。讓對象之間的繼承關係轉變爲關聯關係。算法
裝飾模式能夠在不改變已有對象自己的功能的基礎上給對象增長額外的新職責,比如平常生活中的照片,能夠給照片使用相框,使之具備防潮的功能,可是這樣並無改變照片自己,這即是裝飾模式。ide
abstract class Component { public abstract void Operation(); }
class SpecificComponent : Component { public override void Operation() { //實現基本功能 } }
class Decorator : Component { private Component m_Component; public Decorator(Component component) { this.m_Component = component; } public override void Operation() { //調用原有業務的方法,並未真正裝飾,具體裝飾交給子類 this.m_Component.Operation(); } }
class SpecificDecorator : Decorator { public SpecificDecorator(Component component) : base(component) { } public override void Operation() { //調用原有的業務方法 base.Operation(); //調用新增的業務方法 this.AddedBehavior(); } //新增業務方法 private void AddedBehavior() { //具體裝飾 } }
開發一個能夠對字符串進行加密的數據加密模塊。提供最簡單的加密算法字母移動實現;提供稍微複雜的逆向輸出加密;提供更爲高級的求模加密。用戶先使用最簡單的加密算法進行加密,若是以爲還不夠能夠對加密後的結果進行二次加密甚至三次加密,使用裝飾模式設計。性能
代碼this
abstract class EncryptionComponent { public abstract void EncryptionOperation(string str); } class Encryption : EncryptionComponent { public override void EncryptionOperation(string str) { Console.WriteLine("對字符串: {0}進行位移加密", str); } } //抽象裝飾類 class ComponentDecorator : EncryptionComponent { private EncryptionComponent m_Component; public ComponentDecorator(EncryptionComponent component) { this.m_Component = component; } public override void EncryptionOperation(string str) { this.m_Component.EncryptionOperation(str); } } //逆序加密裝飾類(具體裝飾類) class ReverseDecorator : ComponentDecorator { public ReverseDecorator(EncryptionComponent component) : base(component) { } public override void EncryptionOperation(string str) { base.EncryptionOperation(str); this.ReverseEncryption(str); } private void ReverseEncryption(string str) { Console.WriteLine("對字符串: {0}進行逆序加密", str); } } //求模加密裝飾類(具體裝飾類) class ModDecorator : ComponentDecorator { public ModDecorator(EncryptionComponent component) : base(component) { } public override void EncryptionOperation(string str) { base.EncryptionOperation(str); this.ModEncryption(str); } private void ModEncryption(string str) { Console.WriteLine("對字符串: {0}進行求模加密", str); } }
static void Main() { EncryptionComponent component = new Encryption(); //不進行裝飾 component.EncryptionOperation("裝飾模式"); Console.ReadKey(); }
運行結果加密
static void Main() { EncryptionComponent component = new Encryption(); EncryptionComponent decorate = new ReverseDecorator(component); decorate.EncryptionOperation("裝飾模式"); Console.ReadKey(); }
運行結果spa
static void Main() { EncryptionComponent component = new Encryption(); EncryptionComponent decorate = new ReverseDecorator(component); decorate = new ModDecorator(decorate); decorate.EncryptionOperation("裝飾模式"); Console.ReadKey(); }
運行結果設計