Java工厂方法高速缓存 [英] Java factory method caching
问题描述
我必须开发一些像生活游戏。为此,我有一个名为 CellPosition
的类,它具有 x
和 y
字段。为了有效地使用内存,我想使用某种工厂方法。
I have to develop something like a game of life. For that, I have a class called CellPosition
that has x
and y
fields. In order to efficiently use memory, I would like to use some kind of factory method.
CellPosition.at(int x,int y) / code>,它将返回
CellPosition
的实例。我想缓存具有相同 x,y
对的对象。我虽然一个列表
或一个 HashMap
,但我不知道该使用什么作为一个键。在字符串中连接 x
和 y
是一个好主意。
CellPosition.at(int x, int y)
which would return an instance of CellPosition
. I would like though to cache the objects that have the same x, y
pair. I though of a List
or a HashMap
, but I cannot figure out what to use as a key. A concatenation of x
and y
in a string is doubtingly a good idea.
另一方面,这是一个好主意,每次创建一个对象,只需重新定义 equals()
On the other hand, is it a good idea to just create an object each time and just redefine the equals()
method to compare the objects and throw away any caching?
推荐答案
如果你不介意使用 Guava ,只是:
If you don't mind using Guava, just:
- 使
CellPosition
实例不可变,然后 - 使用
Interner< CellPosition>
(从Interners
),然后 - 继续解决实际问题。
- Make
CellPosition
instances immutable, then - Use an
Interner<CellPosition>
(obtained fromInterners
), then - Move on to solving real problems.
像这样:
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 < a href =http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/cache/Cache.html =nofollow> 缓存
而不是 Interner
,但没有太多意义,因为你必须为缓存构造一个int对密钥 - 对于内部人员,无论如何,减少LoC。
You could also use a Guava Cache
instead of an Interner
, but there's not much point since you'd have to construct an int-pair key for the cache — which you're doing anyway for the interner, in fewer LoC.
这篇关于Java工厂方法高速缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!