Fre*_*ies 1 java concurrency design-patterns
我必须开发类似生命游戏的东西.为此,我有一个名为CellPositionhas x和yfields的类.为了有效地使用内存,我想使用某种工厂方法.
CellPosition.at(int x, int y)这会返回一个实例CellPosition.我想缓存具有相同x, y对的对象.我虽然是a List或a HashMap,但我无法弄清楚要用什么作为关键.的串联x,并y在一个字符串半信半疑地是一个好主意.
另一方面,每次只创建一个对象并重新定义equals()方法来比较对象并丢弃任何缓存是一个好主意吗?
如果你不介意使用番石榴,只需:
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 */}
}
Run Code Online (Sandbox Code Playgroud)
你也可以使用Guava Cache而不是a Interner,但是没有太大的意义,因为你必须为缓存构建一个int-pair密钥 - 无论如何你都要用更少的LoC为interner做.
| 归档时间: |
|
| 查看次数: |
2087 次 |
| 最近记录: |