Decorator pattern in the .NET BCL

The decorator pattern attaches additional responsibilities to an object dynamically. The inheritance is always not feasible, because it is static and applies to an entire class. Decorators provide a flexible alternative to sub-classing for extending functionality. The pattern helps add behavior or state to individual objects at runtime. The .NET Framework uses decorators in the case of stream processing classes. The hierarchy of stream processing classes are as follows:

  • System.IO.Stream
    • System.IO.BufferedStream
    • System.IO.FileStream
    • System.IO.MemoryStream
    • System.Net.Sockets.NetworkStream
    • System.Security.Cryptography.CryptoStream

The following code snippets show how one can use FileStream to read contents from an operating system disk file:

    using (FileStream fs = new FileStream(path, FileMode.Open))  
    { 
      using (StreamReader sr = new StreamReader(fs))  
      { 
        while (sr.Peek() >= 0)  
        { 
          Console.WriteLine(sr.ReadLine()); 
        } 
      } 
    } 

The StreamReader is a decorator object, which uses the additional functionality of buffering the avoid disk access to speed up operation.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.79.59