0

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

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

EntityCollection Foo;
EntityCollection Bar;

我想实现一个将Qux列表 Foo 中的对象移动到 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方法属于哪里?为什么?

4

3 回答 3

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
}
于 2009-07-23T20:13:45.493 回答
1

最终,我认为这并不重要,所以我的温和回答是不要担心。

从语言上讲,MoveTo 似乎比 MoveFrom 更自然——尽管我可以想象为了完整性而实现两者。

从概念上讲,在我看来,集合实例和被移动的实体都不是对移动“负责”,这可能会让我倾向于把它作为一种静态方法——否则你对三件事之一赋予了一些额外的重要性在操作中。

构建一个 Holder 来完成这个动作似乎有点过分了。

但这真的取决于你,更多关于这些东西通常如何消费的知识可能会告诉你什么是“正确”的解决方案。

于 2009-07-24T02:10:31.103 回答
0

使用扩展方法怎么样?

客户端代码将是:

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

签名:

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

流利

于 2009-07-23T20:08:50.277 回答