在閱讀了很多不同的設計模式之後,我得到了關於當前項目的問題,希望有人能幫助我。將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,因爲它用於解析用戶內容並將其傳遞給其他插件?
我希望有人能幫助我解答我的許多問題。
問候, 格里特
謝謝你的回答! SRP也是我更喜歡ParseController的原因。 最後一個問題:在這個例子中,UserContent類是否是DTO(因爲解析數據並將其傳遞給插件)是否正確?或者它是一個商業實體? – Gerrit 2013-02-27 13:35:52
這取決於你的上下文。如果您正在考慮分離解析器,那麼解析器將成爲一個不同的應用程序,並將其定義爲暴露它自己的一組類的合約。如果它們非常可靠,那麼解析器可以直接導出您的業務實體。這一切都取決於您想要添加到應用程序的抽象程度。 – tucaz 2013-02-27 13:47:54