Java工厂方法缓存

标签 java design-patterns concurrency

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

CellPosition.at(int x, int y) 将返回 CellPosition 的实例。我想缓存具有相同 x, y 对的对象。我想到了一个 List 或一个 HashMap,但我不知道要用什么作为键。在字符串中连接 xy 无疑是个好主意。

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

最佳答案

如果你不介意使用 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 */}
}   

您也可以使用 Guava Cache 而不是 Interner ,但没有多大意义,因为您必须为缓存构建一个 int 键对——无论如何,您正在为内部人员做这件事,而且 LoC 更少。

关于Java工厂方法缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10131367/

相关文章:

java - getView() 从未在自定义适配器上调用过

java - eclipse 不支持在 gwt web 项目的服务器包中创建 servlet

java - 如何获取下拉列表的参数值?

c# - XElement 的添加操作是线程安全的吗?

java - Spring Security/expired-url 无重定向 url

java - activemq 5.9.0 在 Windows 和 Maven 中失败

oop - 我们什么时候需要抽象类,如果我们可以使用组合来共享代码,加上接口(interface)来实现多态性?

design-patterns - 什么是命令总线?

database - 将两个完全不同的类作为一个类

scala - 为什么使用复制比串行执行慢得多?