最佳实践以及如何实现需要支持不同类型对象的RealmList
Best practice and how to implement RealmList that need to support different types of objects
我有一个模型 'A',它有一个列表,可以是 'B' 或 'C' 等类型。
我知道 Realm 不支持多态性,我不能只做 RealmList<RealmObject>
或 RealmList<? extends RealmObject>
.
我只是不知道如何用 Realm 实现这种行为。
此处跟踪多态性支持:https://github.com/realm/realm-java/issues/761 , but as long as it isn't implemented you have to use composition instead (https://en.wikipedia.org/wiki/Composition_over_inheritance)
在您的情况下,它看起来像这样:
public interface MyContract {
int calculate();
}
public class MySuperClass extends RealmObject implements MyContract {
private A a;
private B b;
private C c;
@Override
public int calculate() {
return getObj().calculate();
}
private MyContract getObj() {
if (a != null) return a;
if (b != null) return b;
if (c != null) return c;
}
public boolean isA() { return a != null; }
public boolean isB() { return b != null; }
public boolean isC() { return c != null; }
// ...
}
我有一个模型 'A',它有一个列表,可以是 'B' 或 'C' 等类型。
我知道 Realm 不支持多态性,我不能只做 RealmList<RealmObject>
或 RealmList<? extends RealmObject>
.
我只是不知道如何用 Realm 实现这种行为。
此处跟踪多态性支持:https://github.com/realm/realm-java/issues/761 , but as long as it isn't implemented you have to use composition instead (https://en.wikipedia.org/wiki/Composition_over_inheritance)
在您的情况下,它看起来像这样:
public interface MyContract {
int calculate();
}
public class MySuperClass extends RealmObject implements MyContract {
private A a;
private B b;
private C c;
@Override
public int calculate() {
return getObj().calculate();
}
private MyContract getObj() {
if (a != null) return a;
if (b != null) return b;
if (c != null) return c;
}
public boolean isA() { return a != null; }
public boolean isB() { return b != null; }
public boolean isC() { return c != null; }
// ...
}