我必须开发类似生活游戏的东西。为此,我有一个名为 CellPosition
的类,它具有 x
和 y
字段。为了有效地使用内存,我想使用某种工厂方法。
CellPosition.at(int x, int y)
将返回 CellPosition
的实例。我想缓存具有相同 x, y
对的对象。我想到了一个 List
或一个 HashMap
,但我不知道要用什么作为键。在字符串中连接 x
和 y
无疑是个好主意。
另一方面,每次只创建一个对象并重新定义 equals()
方法来比较对象并丢弃任何缓存是否是个好主意?
最佳答案
如果你不介意使用 Guava ,只是:
- 制作
CellPosition
实例不可变,然后 - 使用
Interner<CellPosition>
(从Interners
获得),然后 - 继续解决实际问题。
像这样:
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 */}
}
您也可以使用 Guava Cache
而不是 Interner
,但没有多大意义,因为您必须为缓存构建一个 int 键对——无论如何,您正在为内部人员做这件事,而且 LoC 更少。
关于Java工厂方法缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10131367/