C# 如何改进此存储库设计?
在我当前的设计中,我创建了一个存储库,它由一个字典组成,您可以在其中将几个名为Foo的对象设置为简单、中等和困难的级别。即 简单级别:Foo1对象、Foo2对象、Foo3对象 中级:Foo4对象 硬级别:Foo5对象,Foo6对象 这是我的存储库:C# 如何改进此存储库设计?,c#,repository,uml,repository-pattern,C#,Repository,Uml,Repository Pattern,在我当前的设计中,我创建了一个存储库,它由一个字典组成,您可以在其中将几个名为Foo的对象设置为简单、中等和困难的级别。即 简单级别:Foo1对象、Foo2对象、Foo3对象 中级:Foo4对象 硬级别:Foo5对象,Foo6对象 这是我的存储库: public interface IFoosRepository { void AddFooLevel(Levels level, Foo foo); void RemoveFooLevel(Levels level); Fo
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;
}
}
然后,我意识到另一件事,我需要一个唯一的ID,比如foos对象的名称。也就是说,如果我想从一个级别获得一个特定的对象,我需要设置名称来获取它
现在,对象将如下所示:
简单级别:[名称:foo1,foo1对象],[名称:foo2,foo2对象],[名称:foo3,foo3对象]
中级:[名称:foo4,foo4对象]
硬级别:[名称:foo5,foo5对象],[名称:foo7,Foo6对象]
我的意思是,每个名字都有一个唯一的名字,我想最好不要再重复这个名字了
我开始怀疑我的第一个设计。我的第一个想法是IDictionary>,或者我应该在Foo属性中包含这个id,但我想这不是最好的解决方案
我应该修改什么来实现这个新功能?嵌套字典怎么样?级别字典、字符串字典、Foo如果不知道存储库将如何使用,很难确定,但嵌套字典似乎就是您想要的。例如,在FoosRepository类中:
private IDictionary<Levels,IDictionary<string,Foo> _foos = new Dictionary<Levels,IDictionary<string,Foo>>;
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 );
}