2

我必须开发一些类似生活游戏的东西。为此,我有一个名为CellPositionhasxyfields 的类。为了有效地使用内存,我想使用某种工厂方法。

CellPosition.at(int x, int y)这将返回一个CellPosition. 我想缓存具有相同x, y对的对象。我虽然是 aList或 a HashMap,但我不知道用什么作为键。x将and串联y在一个字符串中无疑是一个好主意。

另一方面,每次只创建一个对象并重新定义equals()方法来比较对象并丢弃任何缓存是否是个好主意?

4

3 回答 3

6

如果您不介意使用Guava,只需:

  1. 使CellPosition实例不可变,然后
  2. 使用Interner<CellPosition>(从 获得Interners),然后
  3. 继续解决实际问题。

像这样的东西:

class CellPosition
{
    private static final Interner<CellPosition> CACHE = Interners.newStrongInterner();
    // or .newWeakInterner(), to allow instances to be garbage collected

    private final int x;
    private final int y;

    private CellPosition(int x, int y)
    {
        this.x = x;
        this.y = x;
    }

    public int x() { return x; }
    public int y() { return y; }

    public static CellPosition at(int x, int y)
    {
        return CACHE.intern(new CellPosition(x, y));
    }

    @Override
    public boolean equals(Object other) {/* TODO */}

    @Override
    public int hashCode() {/* TODO */}
}   

您也可以使用 GuavaCache而不是Interner,但没有什么意义,因为您必须为缓存构造一个 int-pair 密钥——无论如何您都在为内部人员做这件事,而且在更少的 LoC 中。

于 2012-04-12T20:37:02.880 回答
1

我认为缓存这些对象是没有必要的,特别是如果它们像你暗示的那样非常小。一开始你能做的正是你所描述的,CellPosition作为一个值对象,它是不可变的;并正确实施equalshashCode

于 2012-04-12T22:58:52.710 回答
0

您可以使用来自jcabi-aspects 的@CacheableAOP 和注释:

class CellPosition {
  @Cacheable(forever = true)
  public static CellPosition at(int x, int y) {
    // instantiate and return
  }
}
于 2013-02-03T07:38:20.627 回答