【问题标题】:How to improve this repository design?如何改进这个存储库设计?
【发布时间】:2012-04-01 19:57:14
【问题描述】:

在我当前的设计中,我创建了一个存储库,它由一个字典组成,您可以在其中将多个名为 Foo 的对象设置为一个级别(简单、中等和硬)。即。

  • Level Easy: Foo1 对象、Foo2 对象、Foo3 对象
  • 中等级别: Foo4 对象
  • Level Hard: Foo5 对象,Foo6 对象

这是我的存储库:

public interface IFoosRepository
{
    void AddFooLevel(Levels level, Foo foo);
    void RemoveFooLevel(Levels level);
    Foo GetProblemFoo(Levels level);
    IEnumerable<Levels> GetFooLevels();
    IEnumerable<Foo> GetFoos();
}

public class FoosRepository : IFoosRepository
{
    private IFoosService service;
    private Dictionary<Levels, Foo> _fooLevels = new Dictionary<Levels, Foo>();

    public FoosRepository()
        : this(new FoosService())
    {
    }

    public FoosRepository(IFoosService service)
    {
        this.service = service;

        // Loads data into the _fooLevels
        // ...
    }

    public void AddFooLevel(Levels level, Foo foo)
    {
        _FooLevels.Add(level, foo);
    }

    public void RemoveFooLevel(Levels level)
    {
        _FooLevels.Remove(level);
    }

    public Foo GetProblemFoo(Levels level)
    {
        return _FooLevels[level];
    }

    public IEnumerable<Levels> GetFooLevels()
    {
        return _FooLevels.Keys;
    }

    public IEnumerable<Foo> GetFoos()
    {
        return _FooLevels.Values;
    }
}

然后,我意识到另一件事,我需要一个 uniqueId,例如 foos 对象的名称。 IE。如果我想从一个关卡中获得一个特定的对象,我需要设置名称来获取它。

现在对象会是这样的:

  • 简单级别: [name:foo1, Foo1 object], [name:foo2, Foo2 object], [name:foo3, Foo3 object]
  • 中等级别: [name:foo4, Foo4 object]
  • 难度级别: [name:foo5, Foo5 object], [name:foo7, Foo6 object]

我的意思是,每个名字都伴随着一个唯一的名字,我想这个名字最好不要在另一个名字中重复。

这时我开始怀疑我的第一个设计。我的第一个想法是 IDictionary>,或者我应该将这个 id 包含到 Foo 属性中,但我想这不是最好的解决方案。

我应该修改什么来实现这个新功能?

【问题讨论】:

    标签: c# repository uml repository-pattern


    【解决方案1】:

    嵌套字典怎么样? Dictionary(of Levels, Dictionary(of String, Foo))

    【讨论】:

      【解决方案2】:

      如果不了解您的存储库将如何使用的更多信息,很难确定,但嵌套字典似乎正是您想要的。例如,在您的 FoosRepository 类中:

      private IDictionary<Levels,IDictionary<string,Foo> _foos = new Dictionary<Levels,IDictionary<string,Foo>>;
      

      然后,例如,您的 AddFooLevel 将变为:

      public AddFooLevel( Levels level, string name, Foo foo ) {
        IDictionary<string,Foo> level = null;
        if( _foos.ContainsKey( level ) ) {
          level = _foos[level];
        } else {
          level = new Dictionary<string,Foo>();
          _foos.Add( level );
        }
        level.Add( name, foo );
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-01-21
        • 2011-01-27
        • 2023-03-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-09
        相关资源
        最近更新 更多