本文转自一下博客:装饰模式html
装饰(Decorator)模式又名包装(Wrapper)模式[GOF95]。装饰模式以对客户端透明的方式扩展对象的功能,是继承关系的一个替代方案。编程
引言app
孙悟空有七十二般变化,他的每一种变化都给他带来一种附加的本领。他变成鱼儿时,就能够到水里游泳;他变成雀儿时,就能够在天上飞行。而无论悟空怎么变化,在二郎神眼里,他永远是那只猢狲。ide
装饰模式以对客户透明的方式动态地给一个对象附加上更多的责任。换言之,客户端并不会以为对象在装饰前和装饰后有什么不一样。装饰模式能够在不使用创造更多子类的状况下,将对象的功能加以扩展。函数
装饰模式使用原来被装饰的类的一个子类的实例,把客户端的调用委派到被装饰类。装饰模式的关键在于这种扩展是彻底透明的。性能
在孙猴子的例子里,老孙变成的鱼儿至关于老孙的子类,这条鱼儿与外界的互动要经过"委派",交给老孙的本尊,由老孙本尊采起行动。this
装饰模式的类图以下图所示:spa
在装饰模式中的各个角色有:.net
如下示例性代码实现了装饰模式:设计
// Decorator pattern -- Structural example using System; // "Component" abstract class Component { // Methods abstract public void Operation(); } // "ConcreteComponent" class ConcreteComponent : Component { // Methods override public void Operation() { Console.WriteLine("ConcreteComponent.Operation()"); } } // "Decorator" abstract class Decorator : Component { // Fields protected Component component; // Methods public void SetComponent( Component component ) { this.component = component; } override public void Operation() { if( component != null ) component.Operation(); } } // "ConcreteDecoratorA" class ConcreteDecoratorA : Decorator { // Fields private string addedState; // Methods override public void Operation() { base.Operation(); addedState = "new state"; Console.WriteLine("ConcreteDecoratorA.Operation()"); } } // "ConcreteDecoratorB" class ConcreteDecoratorB : Decorator { // Methods override public void Operation() { base.Operation(); AddedBehavior(); Console.WriteLine("ConcreteDecoratorB.Operation()"); } void AddedBehavior() { } } /// <summary> /// Client test /// </summary> public class Client { public static void Main( string[] args ) { // Create ConcreteComponent and two Decorators ConcreteComponent c = new ConcreteComponent(); ConcreteDecoratorA d1 = new ConcreteDecoratorA(); ConcreteDecoratorB d2 = new ConcreteDecoratorB(); // Link decorators d1.SetComponent( c ); d2.SetComponent( d1 ); d2.Operation(); } }
上面的代码在执行装饰时是经过SetComponent方法实现的,在实际应用中,也有经过构造函数实现的,一个典型的建立过程可能以下:
new Decorator1( new Decorator2( new Decorator3( new ConcreteComponent() ) ) )
装饰模式经常被称为包裹模式,就是由于每个具体装饰类都将下一个具体装饰类或者具体构件类包裹起来。
在如下状况下应当使用装饰模式:
该例子演示了经过装饰模式为图书馆的图书与录像带添加"可借阅"装饰。
// Decorator pattern -- Real World example using System; using System.Collections; // "Component" abstract class LibraryItem { // Fields private int numCopies; // Properties public int NumCopies { get{ return numCopies; } set{ numCopies = value; } } // Methods public abstract void Display(); } // "ConcreteComponent" class Book : LibraryItem { // Fields private string author; private string title; // Constructors public Book(string author,string title,int numCopies) { this.author = author; this.title = title; this.NumCopies = numCopies; } // Methods public override void Display() { Console.WriteLine( " Book ------ " ); Console.WriteLine( " Author: {0}", author ); Console.WriteLine( " Title: {0}", title ); Console.WriteLine( " # Copies: {0}", NumCopies ); } } // "ConcreteComponent" class Video : LibraryItem { // Fields private string director; private string title; private int playTime; // Constructor public Video( string director, string title, int numCopies, int playTime ) { this.director = director; this.title = title; this.NumCopies = numCopies; this.playTime = playTime; } // Methods public override void Display() { Console.WriteLine( " Video ----- " ); Console.WriteLine( " Director: {0}", director ); Console.WriteLine( " Title: {0}", title ); Console.WriteLine( " # Copies: {0}", NumCopies ); Console.WriteLine( " Playtime: {0}", playTime ); } } // "Decorator" abstract class Decorator : LibraryItem { // Fields protected LibraryItem libraryItem; // Constructors public Decorator ( LibraryItem libraryItem ) { this.libraryItem = libraryItem; } // Methods public override void Display() { libraryItem.Display(); } } // "ConcreteDecorator" class Borrowable : Decorator { // Fields protected ArrayList borrowers = new ArrayList(); // Constructors public Borrowable( LibraryItem libraryItem ) : base( libraryItem ) {} // Methods public void BorrowItem( string name ) { borrowers.Add( name ); libraryItem.NumCopies--; } public void ReturnItem( string name ) { borrowers.Remove( name ); libraryItem.NumCopies++; } public override void Display() { base.Display(); foreach( string borrower in borrowers ) Console.WriteLine( " borrower: {0}", borrower ); } } /// <summary> /// DecoratorApp test /// </summary> public class DecoratorApp { public static void Main( string[] args ) { // Create book and video and display Book book = new Book( "Schnell", "My Home", 10 ); Video video = new Video( "Spielberg", "Schindler's list", 23, 60 ); book.Display(); video.Display(); // Make video borrowable, then borrow and display Console.WriteLine( " Video made borrowable:" ); Borrowable borrowvideo = new Borrowable( video ); borrowvideo.BorrowItem( "Cindy Lopez" ); borrowvideo.BorrowItem( "Samuel King" ); borrowvideo.Display(); } }
使用装饰模式主要有如下的优势:
使用装饰模式主要有如下的缺点:
因为使用装饰模式,能够比使用继承关系须要较少数目的类。使用较少的类,固然使设计比较易于进行。可是,在另外一方面,使用装饰模式会产生比使用继承关系更多的对象。更多的对象会使得查错变得困难,特别是这些对象看上去都很相像。
大多数状况下,装饰模式的实现都比上面定义中给出的示意性实现要简单。对模式进行简化时须要注意如下的状况:
(1)一个装饰类的接口必须与被装饰类的接口相容。
(2)尽可能保持Component做为一个"轻"类,不要把太多的逻辑和状态放在Component类里。
(3)若是只有一个ConcreteComponent类而没有抽象的Component类(接口),那么Decorator类常常能够是ConcreteComponent的一个子类。以下图所示:
(4)若是只有一个ConcreteDecorator类,那么就没有必要创建一个单独的Decorator类,而能够把Decorator和ConcreteDecorator的责任合并成一个类。
透明的装饰模式
装饰模式一般要求针对抽象编程。装饰模式对客户端的透明性要求程序不要声明一个ConcreteDecorator类型的变量,而应当声明一个Component类型的变量。换言之,下面的作法是对的:
Component c = new ConcreteComponent(); Component c1 = new ConcreteDecorator1(c); Component c2 = new ConcreteDecorator(c1);
而下面的作法是不对的:
ConcreteComponent c = new ConcreteDecorator();
这就是前面所说的,装饰模式对客户端是彻底透明的含义。
用孙悟空的例子来讲,必须永远把孙悟空的全部变化都当成孙悟空来对待,而若是把老孙变成的雀儿当成雀儿,而不是老孙,那就被老孙骗了,而这是不该当发生的。
下面的作法是不对的:
大圣本尊 c = new 大圣本尊(); 雀儿 bird = new 雀儿 (c);
半透明的装饰模式
然而,纯粹的装饰模式很难找到。装饰模式的用意是在不改变接口的前提下,加强所考虑的类的性能。在加强性能的时候,每每须要创建新的公开的方法。即使是在孙大圣的系统里,也须要新的方法。好比齐天大圣类并无飞行的能力,而雀儿有。这就意味着雀儿应当有一个新的fly()方法。
这就致使了大多数的装饰模式的实现都是"半透明"(semi-transparent)的,而不是彻底"透明"的。换言之,容许装饰模式改变接口,增长新的方法。即声明ConcreteDecorator类型的变量,从而能够调用ConcreteDecorator类中才有的方法:
齐天大圣 c = new 大圣本尊(); 雀儿 bird = new 雀儿(c); bird.fly();
齐天大圣接口根本没有fly()这个方法,而雀儿接口里有这个方法。
.net中存在以下类模型:
下面的代码段用来将XmlDocument的内容格式输出。咱们能够体会Decorator模式在这里所起的做用。
// 生成ConcreteComponent(内存流ms) MemoryStream ms = new MemoryStream(); // 用XmlTextWriter对内存流 ms 进行装饰 // 此处使用了半透明的装饰模式 XmlTextWriter xtw = new XmlTextWriter(ms, Encoding.UTF8); xtw.Formatting = Formatting.Indented; // 对装饰xtw的操做会转而操做本体-内存流ms xmlDoc.Save(xtw); byte[] buf = ms.ToArray(); txtResult.Text = Encoding.UTF8.GetString(buf,0,buf.Length); xtw.Close();