实例解析C#设计模式编程中简单工厂模式的使用

2019-12-26 18:02:51王冬梅

 

.NET中简单工厂模式的实现
  介绍完了简单工厂模式之后,我学习的时候就像:.NET类库中是否有实现了简单工厂模式的类呢?后面确实有,.NET中System.Text.Encoding类就实现了简单工厂模式,该类中的GetEncoding(int codepage)就是工厂方法,具体的代码可以通过Reflector反编译工具进行查看,下面我也贴出该方法中部分代码:


public static Encoding GetEncoding(int codepage)
{
  Encoding unicode = null;
  if (encodings != null)
  {
    unicode = (Encoding) encodings[codepage];
  }
  if (unicode == null)
  {
    object obj2;
    bool lockTaken = false;
    try
    {
      Monitor.Enter(obj2 = InternalSyncObject, ref lockTaken);
      if (encodings == null)
      {
        encodings = new Hashtable();
      }
      unicode = (Encoding) encodings[codepage];
      if (unicode != null)
      {
        return unicode;
      }
      switch (codepage)
      {
        case 0:
          unicode = Default;
          break;
        case 1:
        case 2:
        case 3:
        case 0x2a:
          throw new ArgumentException(Environment.GetResourceString("Argument_CodepageNotSupported", new object[] { codepage }), "codepage");
        case 0x4b0:
          unicode = Unicode;
          break;
        case 0x4b1:
          unicode = BigEndianUnicode;
          break;
        case 0x6faf:
          unicode = Latin1;
          break;
        case 0xfde9:
          unicode = UTF8;
          break;
        case 0x4e4:
          unicode = new SBCSCodePageEncoding(codepage);
          break;
        case 0x4e9f:
          unicode = ASCII;
          break;
        default:
          unicode = GetEncodingCodePage(codepage);
          if (unicode == null)
          {
            unicode = GetEncodingRare(codepage);
          }
          break;
      }
      encodings.Add(codepage, unicode);
      return unicode;
    }
}

.NET 中Encoding的UML图为:

实例解析C#设计模式编程中简单工厂模式的使用

Encoding类中实现的简单工厂模式是简单工厂模式的一种演变,此时简单工厂类由抽象产品角色扮演,然而.NET中Encoding类是如何解决简单工厂模式中存在的问题的呢(即如果新添加一种编码怎么办)?在GetEncoding方法里的switch函数有如下代码:


switch (codepage)
   {
     .......
  default:
          unicode = GetEncodingCodePage(codepage);
          if (unicode == null)
          {
            unicode = GetEncodingRare(codepage); //当编码很少见时
          }
          break;
      ......
   }