2016-05-16 34 views
2

所以..我有一個對象創建模式的問題。通過多個正則表達式值來預測異議

我有多個canonicalIds例如。

school/1 
school/1/class/12/ 
school/1/class/12/teacher/35 

我有不同的對象代表這些並從id創建。 我想以一種乾淨的方式進行循環,通過正則表達式'並確定它是哪個對象。

我被困在決定如何去匹配正則表達式到特定的工廠方法。

我想提取由字符串中最後一個單詞確定的類型。還包括id,然後將其委派給服務以從數據存儲檢索對象。除了膠水之外,一切都已到位。我覺得有比擁有一個龐大的if/else語句

class Factory() 
{ 
    object create(string value) 
    { 
    if(match1.ismatch(value)) 
    { 
     //getting match groups and then using the values to get an object from a data store 
     var schoolid= mactch.group[1].value; 
     return new SchoolSerice().GetSchool(schoolid); 
    } 
    if(match2.ismatch(value)) 
    {   
     var schoolid= mactch.group[1].value; 
     var classid= mactch.group[2].value; 
     return new SchoolSerice().GetClass(schoolid,classid); 
    } 
    } 
+0

你可以更具體一點你要提取.. – rock321987

+0

與擴展數據 – BastanteCaro

+0

編輯後我能想象在這裏應用策略模式是什麼,但老實說,我看不出有任何好處。代碼將被分散開來,邏輯更難以「看到」。我建議你創建諸如'isSchool()','isClass()'等函數來封裝正則表達式邏輯。它會讓你的'if'語句更具可讀性。 – Fuhrmanator

回答

0

你可能會需要Reflection,這將允許你動態地調用一個方法更好的方法,無論是GetSchoolGetClass或什麼的。你可以看看這個post,因爲我的答案是基於它的。

我只驗證了正則表達式部分,因爲我沒有經歷反射,所以我只是試圖指出你在正確的方向。

正則表達式:"([^\\/]+)\\/([^\\/]+)"

([^\\/]+) # Capture group #1, will capture any character until forward slash, which will be object name 
\\/  #forward slash, 
([^\\/]+) # Capture group #2, will capture any character until forward slash or end of string, which will be id 

的方法名稱將從由Get之前的最後一個匹配的對象名來形成。所有的ID將被放入一個int數組中,該數組將作爲方法調用的參數傳遞。我假設schoolidclassidint,如果你需要它們作爲字符串,只需刪除Int32.Parse()


示例代碼。

class Factory() 
{ 
     object create(string value) 
     { 

      Type type = Type.GetType("SchoolSerice"); 
      Object obj = Activator.CreateInstance(type); 
      MethodInfo methodInfo; 

      string pattern = "([^\\/]+)\\/([^\\/]+)"; 
      string methodName = ""; 
      List<int> argsList = new List<int>(); 
      int[] argsArray; 

      foreach (Match m in Regex.Matches(value, pattern)) 
      { 
       methodName="get"+char.ToUpper(m.Groups[1].Value[0]) + m.Groups[1].Value.Substring(1); 
       argsList.Add(Int32.Parse(m.Groups[2].Value)); 
      } 

      argsArray=argsList.ToArray(); 
      methodInfo = type.GetMethod(methodName); 

      return new methodInfo.Invoke(obj, argsArray); 

     } 
}