技术开发 频道

结构型模式篇-装饰模式(Decorator Pattern)


1..NET中Decorator模式一个典型的运用就是关于Stream,它存在着如下的类结构:


                                                                                            图8
    可以看到, BufferedStream和CryptoStream其实就是两个包装类,这里的Decorator模式省略了抽象装饰角色(Decorator),示例代码如下:
class Program { public static void Main(string[] args) { MemoryStream ms = new MemoryStream(new byte[] { 100,456,864,222,567}); //扩展了缓冲的功能 BufferedStream buff = new BufferedStream(ms); //扩展了缓冲,加密的功能 CryptoStream crypto = new CryptoStream(buff); } }
    通过反编译,可以看到BufferedStream类的代码(只列出部分),它是继承于Stream类:

public sealed class BufferedStream : Stream { // Methods private BufferedStream(); public BufferedStream(Stream stream); public BufferedStream(Stream stream, int bufferSize); // Fields private int _bufferSize; private Stream _s; }
2.在Enterprise Library中的DAAB中有一个DbCommandWrapper的包装类,它实现了对IDbCommand类的包装并提供了参数处理的功能。结构图如下:



                                                                                            图9

示意性代码如下:
public abstract class DBCommandWrapper : MarshalByRefObject, IDisposable { } public class SqlCommandWrapper : DBCommandWrapper { } public class OracleCommandWrapper : DBCommandWrapper { }
0
相关文章