如何解决如何泛化使用对象缓存的工厂方法?
我正在尝试为从公共父级继承的一组类创建静态工厂方法。我的想法是实现类似于 String 的 intern() 方法的东西 - 我想使用工厂方法在使用等效对象时使用单个对象(而不是拥有数千个等效对象)。
请注意,大多数子类没有字段,但其中一些可能有一些字段并具有不同的构造函数参数(在这种情况下,我会覆盖子类的 equals 和 hashCode),因此每个类只使用一个单例是行不通的(无论如何我都不想使用单身人士)。
我已经编写了下面的代码,但是对于每个子类,我必须在工厂方法中复制几乎相同的代码。我尝试使用通用方法编写它,但不知道如何编写。
有什么办法可以避免所有这些丑陋的代码重复?
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;
// possibly more fields
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(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);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。