【问题标题】:Best practice and how to implement RealmList that need to support different types of objects最佳实践以及如何实现需要支持不同类型对象的 RealmList
【发布时间】:2016-04-27 08:39:41
【问题描述】:

我有一个模型“A”,它有一个列表类型可以是“B”或“C”等等。 我知道 Realm 不支持多态性,我不能只做 RealmList<RealmObject>RealmList<? extends RealmObject>

我只是不知道如何用 Realm 实现这种行为。

【问题讨论】:

    标签: android realm realm-list


    【解决方案1】:

    在这里跟踪多态性支持:https://github.com/realm/realm-java/issues/761,但只要未实现,您就必须改用组合 (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; }
    
      // ...
    }
    

    【讨论】:

      猜你喜欢
      • 2020-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多