【发布时间】:2023-04-05 05:31:01
【问题描述】:
我已经编写了一个类似单例的不可变对象池的实现(“单例”是指我只需要每个具有相同字段值的对象的一个副本),如下所示。我不喜欢我必须创建对象只是为了检查池中是否已经有等效对象的事实。有没有办法避免这种情况? (即检查我是否已经在池中拥有我需要的对象,如果它不存在则只创建它)。
注意:不同的子类可以有多个不同的字段或根本没有字段。
public class Parent {
protected static final Map<Parent, WeakReference<Parent>> pool = Collections.synchronizedMap(new WeakHashMap<>());
}
public class Child extends Parent
{
final int field1;
final int field2;
private Child(int field1, int field2) {
this.field1 = field1;
this.field2 = field2;
}
public static Child newChildClass(int field1, int field2) {
Child child = new Child(field1, field2);
Child obj = (Child)pool.get(child).get();
if (obj == null) pool.put(obj = child, new WeakReference<>(child));
return obj;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Child that = (Child) o;
return field1 == that.field1 && field2 == that.field2;
}
@Override
public int hashCode() {
return Objects.hash(getClass(), field1, field2);
}
}
【问题讨论】: