2013-02-27 120 views
4

在閱讀了很多不同的設計模式之後,我得到了關於當前項目的問題,希望有人能幫助我。將usercontent解析到資源庫中。哪種方法更好?

我的項目將不同的用戶文件作爲輸入並將它們轉換爲對象的存儲庫以便於使用。

例如:

Userfile A with the content: 
"id:a" - "value1:contentA1" - "value2:contentB1" 
"id:b" - "value1:contentA2" - "value2:contentB2" 
"id:c" - "value1:contentA3" - "value2:contentB3" 

現在我看到兩種不同的方法來解析該文件爲對象(這是更好?):

1)

我們得到了一個實體類:

public class UserContent 
{ 
    public int ID { get; set; } 
    public string Value1 { get; set; } 
    public string Value2 { get; set; } 
} 

服務需要該用戶文件的一行,將其解析爲對象:

public class UserContentParser 
{ 
    public UserContent ParseUserContent(string content) 
    { 
     // ... 
     // splitting the content 
     // ... 
     return new UserContent 
          { 
           ID = id, 
           Value1 = value1, 
           Value2 = value2 
          }; 
    } 
} 

甲ParseController:

public class ParseController 
{ 
    private Repository _repository = new Repository(); 
    private UserContentParser _userContentParser = new UserContentParser(); 

    public Repository StartParsing(File userFile) 
    { 
     // ... 
     // reading file 
     // ... 
     foreach(var contentLine in userFileContent) 
     { 
      _repository.AddUserContent(_userContentParser.ParseUserContent(contentLine)); 
     } 
    } 
} 

另一種方法我看到的是以下內容:

2) 這approche只有兩個類別(無服務級別):

public class UserContent 
{ 
    public UserContent(string content) 
    { 
     // ... 
     // splitting the content 
     // ... 
     ID = id; 
     Value1 = value1; 
     Value2 = value2; 
    } 

    public int ID { get; set; } 
    public string Value1 { get; set; } 
    public string Value2 { get; set; } 
} 

public class ParseController 
{ 
    private Repository _repository = new Repository(); 
    private UserContentParser _userContentParser = new UserContentParser(); 

    public Repository StartParsing(File userFile) 
    { 
     // ... 
     // reading file 
     // ... 
     foreach(var contentLine in userFileContent) 
     { 
      _repository.NewUserContent(contentLine); 
      // in this method the repository creates the 
      // new UserContent(contentLine) 
     } 
    } 
} 

這些項目還包含一些插件,這些插件獲取對存儲庫的引用以使用包含對象。

這裏哪種方法更好?有沒有更好的選擇?如果需要其他依賴關係來解析用戶內容會發生什麼?如果實體依賴於服務,還是更好地在實體對象中沒有依賴關係,那麼可以嗎?甚至還有一個問題,UserContent類是DTO,因爲它用於解析用戶內容並將其傳遞給其他插件?

我希望有人能幫助我解答我的許多問題。

問候, 格里特

回答

0

你確實有很多問題,他們很難anwser因爲它們依賴於很多您上下文,並暗示你,但不是我們的。另外,我認爲你太擔心太多,並且在你不應該的時候會想太多。

但是,作爲一般建議,您應該遵循SRP並將每個責任歸入其自己的類中,以便將解析器作爲單獨的類使用。有了這個在一個單獨的類將允許你從它提取一個解析器接口,並有多個實現和管理解析器的依賴關係,如果你有這個。

當他們來找你時,或者你知道他們會根據以前的經驗來找你,而不是以前,你應該擔心這個「假設」問題。

+0

謝謝你的回答! SRP也是我更喜歡ParseController的原因。 最後一個問題:在這個例子中,UserContent類是否是DTO(因爲解析數據並將其傳遞給插件)是否正確?或者它是一個商業實體? – Gerrit 2013-02-27 13:35:52

+0

這取決於你的上下文。如果您正在考慮分離解析器,那麼解析器將成爲一個不同的應用程序,並將其定義爲暴露它自己的一組類的合約。如果它們非常可靠,那麼解析器可以直接導出您的業務實體。這一切都取決於您想要添加到應用程序的抽象程度。 – tucaz 2013-02-27 13:47:54