在阅读了许多不同的设计模式后,我收到了一个关于我当前项目的问题,我希望有人能帮助我。
我的项目将不同的用户文件作为输入,并将它们转换为对象存储库以便于使用。
例如:
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
};
}
}
解析控制器:
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) 这个方法只包含两个类(没有服务类):
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,因为它用于将用户内容解析到其中并将其传递给其他插件?
我希望有人可以帮助我解决我的许多问题。
问候,格里特