在列表之间“移动”对象的首选方法

时间:2009-07-23 20:01:01

标签: list methods separation-of-concerns

我有两个单独的实体列表:

class EntityCollection : IList<Entity>
{
    //...
}

EntityCollection Foo;
EntityCollection Bar;

我想实现一个操作,将列表Foo上的对象Qux移动到Bar。实施它的最佳方法是什么?

  • 作为MoveTo上的EntityCollection实例方法:

    public void MoveTo(EntityCollection to, Entity entity);
    
    // Client code
    Foo.MoveTo(Bar, Qux);
    
  • 作为MoveFrom上的EntityCollection实例方法:

    public void MoveFrom(EntityCollection from, Entity entity);
    
    // Client code
    Bar.MoveFrom(Foo, Qux);
    
  • 作为Move上的静态EntityCollection方法:

    public static void Move(Entity entity, EntityCollection from, EntityCollection to);
    
    // Client code
    EntityCollection.Move(Qux, Foo, Bar);
    
  • 作为包含两个集合的类的Move实例方法:

    public void Move(Entity entity, EntityCollection from, EntityCollection to);
    
    // Client code
    Holder.Move(Qux, Foo, Bar);
    

或者,由于实体一次只能在一个集合中,我可以让实体自己跟踪它们的位置,并在实体本身上实现它:

    public void MoveTo(EntityCollection to)
    {
       if(Location != null)
           Location.Remove(this);
       to.Add(this);
       Location = to;
    }

    // Client code
    Entity e;
    e.MoveTo(Foo);

    // Later on...
    e.MoveTo(Bar);

当提出这么多选项时,我想知道:move方法属于哪里?为什么?

3 个答案:

答案 0 :(得分:1)

MoveTo和MoveFrom都将使用对Add()和Remove()的调用,因此您可以在一个函数中执行这两个操作。在这种情况下,你可以这样做:

enum MoveDirection
{
    ToFoo = 0
    ToBar = 1
}

MoveItem(Entity entity, MoveDirection direction)
{
    if direction = 0
       //move entity from Bar to Foo
    elseif direction = 1
       //move entity from Foo to Bar
    endif
}

答案 1 :(得分:1)

最终,我认为这不重要,所以我的回答是不轻易的。

语言学上,MoveTo似乎比MoveFrom更自然 - 尽管我可以想象实现两者的完整性。

从概念上讲,我觉得既不是集合实例也不是被移动的实体对移动是“负责任的”,这可能会让我把它作为静态方法 - 否则你会给它一个额外的重要性。正在运作的三件事。

构建一个持有者然后完成这一举动似乎相当过分。

但这取决于你,并且更多地了解这些事情通常会被消耗掉,这可能会告诉我们“正确”的解决方案是什么。

答案 2 :(得分:0)

如何使用扩展方法?

客户端代码为:

Foo.Move(Qux).To(Bar);

签名:

public static Entity Move(this EntityCollection from, Entity entity)
public static void To(this Entity entity, EntityCollection to)

Fluent