4

在阅读了许多不同的设计模式后,我收到了一个关于我当前项目的问题,我希望有人能帮助我。

我的项目将不同的用户文件作为输入,并将它们转换为对象存储库以便于使用。

例如:

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,因为它用于将用户内容解析到其中并将其传递给其他插件?

我希望有人可以帮助我解决我的许多问题。

问候,格里特

4

1 回答 1

0

您确实有很多问题,而且很难回答,因为它们在很大程度上取决于您的上下文,这对您来说是暗示的,但对我们没有暗示。另外,我认为您在不应该的情况下过多地担心并过多地考虑“如果”。

但是,作为一般建议,您应该遵循SRP并将每个职责放在它自己的类中,因此将解析器作为一个单独的类是有意义的。将它放在一个单独的类中将允许您从中提取一个Parser接口并拥有多个实现并管理解析器的依赖关系(如果您有的话)。

当他们来找你或者当你知道他们会根据以前的经验而不是以前来找你时,你应该担心“假设”问题。

于 2013-02-27T12:27:31.570 回答