2012-04-01 69 views
0

在我當前的設計中,我創建了一個存儲庫,它由一個字典組成,您可以在其中將幾個名爲Foo的對象設置爲一個級別(簡單,中等和難度)。 I.E.如何改進此存儲庫設計?

  • 級別EASY: Foo1對象和Foo2對象,Foo3對象
  • 水平中等: Foo4對象
  • 級硬盤: 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對象的名稱。 I.E.如果我想從一個關卡中獲取特定的對象,我需要設置名稱來獲取它。

現在的對象會是這樣:

  • 級別EASY: [名稱:foo1,Foo1對象],[名字:foo2的和Foo2對象],[名字:foo3,Foo3對象]
  • 等級介質: [名:foo4,Foo4對象]
  • 等級硬: [名:foo5,Foo5對象],[名稱:foo7,Foo6對象]

我的意思是,每個名字都伴隨着一個獨特的名字,我想這將是最好的,這個名字不會在另一個更多的重複。

這是當我開始懷疑我的第一個設計。我的第一個雖然是IDictionary>,或者我應該不得不包括這個ID到Foo屬性,但我想這不是最好的解決方案。

我應該修改什麼來實現這個新功能?

回答

0

嵌套字典怎麼樣?字典(級別,字典(的字符串,美孚))

0

很難肯定地說,不知道更多關於你的存儲庫將如何使用,但嵌套字典似乎是你想要的。例如,在你的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); 
}