[Template] 工廠 + 泛型 + Strategy

[Template] 工廠 + 泛型 + Strategy

(註: 本文只有空殼沒有實作內容. 只是方便筆者記錄而已!)

 

還蠻常用到的架構, 筆記下來, 有空再來做 code generator

 

下面的範例是為了符合不同的json format string產生口語化的描述.

先用工廠 + 泛型 處理核心邏輯

   1:      public class LogDescFactory
   2:      {
   3:          public enum LogType
   4:          {
   5:              SaveRole
   6:          }
   7:          public static LogDesc GetLogDesc(LogType type)
   8:          {
   9:              switch (type)
  10:              {
  11:                  case LogType.SaveRole:
  12:                      return new LogDescSaveRole();
  13:              }
  14:              return null;
  15:          }
  16:      }
  17:   
  18:      public interface LogDesc
  19:      {
  20:          string GetDescription(string json);
  21:      }
  22:      
  23:      public abstract class BaseLogDesc<T> : LogDesc
  24:          where T : BaseLogObject
  25:      {
  26:   
  27:          #region LogDesc 成員
  28:   
  29:          public string GetDescription(string json)
  30:          {
  31:   
  32:              throw new NotImplementedException();
  33:          }
  34:   
  35:          #endregion
  36:      }
  37:   
  38:      public class BaseLogObject
  39:      {
  40:          public string Method { get; set; }
  41:      }
  42:   
  43:      public class LogObjectSaveRole : BaseLogObject
  44:      {
  45:      }
  46:   
  47:      public class LogDescSaveRole : BaseLogDesc<LogObjectSaveRole>
  48:      {
  49:   
  50:      }

 

 

簡單的 Strategy pattern 去處理列印不同策略下的文字描述

 

   1:  public class Context
   2:      {
   3:          private LogDesc logDesc;
   4:   
   5:          public Context(LogDesc desc){
   6:              this.logDesc = desc;
   7:          }
   8:   
   9:          public void Print(string json)
  10:          {
  11:              Console.WriteLine(this.logDesc.GetDescription(json));
  12:          }
  13:      }
  14:   
  15:      public class MainTest
  16:      {
  17:          public static void Main()
  18:          {
  19:              Context context = new Context(LogDescFactory.GetLogDesc(LogDescFactory.LogType.SaveRole));
  20:   
  21:              context.Print(@"{""ACTION"":""SAVE_ROLE"",""USER"":""hector.lee""}");
  22:          }
  23:      }