Saturday, September 21, 2013

I want to post some samples of select design patterns:
1) Builder pattern - This pattern separates the construction of a complex object from its representation so that the same construction process can create different representations.
public class RTFReader
{
   private TextConverter builder;
   public RTFReader( TextConverter t )
  {
    builder = t;
   }
   public void ParseRTF()
   {
              var t = token.Next();
              while (t != null)
             {
                switch( typeof(t))
                {
                    CHAR:
                      builder->ConvertCharacter(t.Char);
                    FONT:
                      builder->ConvertFont(t.Font);
                    PARA:
                     builder->ConvertParagraph(t.Para);
                 }
              }
    }
}

public abstract class TextConverter
{
   public ConvertCharacter(CHAR);
   public ConvertFont(FONT);
   public ConvertParagraph(PARA);
}

BTW - StringBuilder in .Net is not a design pattern.

Factory Pattern: Here we use an interface for creating an object but let the sub-classes decide the class to instantiate. In .Net library, we use for example a WebRequest class that is used to make a request and receive a response.

public static class WebRequest {

public static WebRequest Create(string);
}
The Create method creates various instances of the WebRequest class such as HttpWebRequest, FileWebRequest, FTPWebRequest etc.

Adaptor  Pattern: These can be often confused with Decorator patterns but they are different.
The Decorator patterns extend functionality dynamically. The Adaptors make one interface work with another so they change interfaces unlike the decorator.

SqlClient is an adapter pattern. Each provider is an adapter for its specific database. A class adapter uses multiple inheritance to adapt interfaces.

public sealed class SqlDataAdapter : DbDataAdapter, IDbDataAdapter, IDataAdapter, ICloneable
{
}

The key here is to inherit one and implement the other

No comments:

Post a Comment