Java工厂方法缓存

Fre*_*ies 1 java concurrency design-patterns

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

CellPosition.at(int x, int y)这会返回一个实例CellPosition.我想缓存具有相同x, y对的对象.我虽然是a List或a HashMap,但我无法弄清楚要用什么作为关键.的串联x,并y在一个字符串半信半疑地是一个好主意.

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

Mat*_*all 6

如果你不介意使用番石榴,只需:

  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 */}
}   
Run Code Online (Sandbox Code Playgroud)

你也可以使用Guava Cache而不是a Interner,但是没有太大的意义,因为你必须为缓存构建一个int-pair密钥 - 无论如何你都要用更少的LoC为interner做.

  • 你可以用vanilla Java做同样的事情,但我没有看到一个令人信服的理由在这里重新发明轮子.除了番石榴是一个很棒的图书馆 - 一旦你开始使用它,你会喜欢它. (2认同)