装饰模式是一种用于代替继承的技术,达到无需定义子类却能够给对象动态增长职责的效果。让对象之间的继承关系转变为关联关系。算法
装饰模式能够在不改变已有对象自己的功能的基础上给对象增长额外的新职责,比如平常生活中的照片,能够给照片使用相框,使之具备防潮的功能,可是这样并无改变照片自己,这即是装饰模式。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(); }
运行结果设计