Composition Over Inheritance For Realmobjects With Gson Serialization
I'm considering Realm as a database solution for various reasons, but the big one currently being the TransactionTooLargeException now being thrown in Nougat has made it so I have
Solution 1:
You should create a new RealmObject class for each flattened concrete class, and map your JSON representation to them.
To retain inheritance, you can simulate it by inheriting getters/setters from interfaces that inherit from one another.
publicinterfaceIAnimalextendsRealmModel {
intgetNumberOfLegs();
voidsetNumberOfLegs(int legs);
booleangetHasFur();
voidsetHasFur(boolean hasFur);
}
publicinterfaceIDogextendsIAnimal {
String getColor();
voidsetColor(String color);
booleangetCanDoTricks();
voidsetCanDoTricks();
}
publicinterfaceIGermanShepherdextendsIDog {
booleangetIsGuardDog();
voidsetIsGuardDog(boolean isGuardDog);
booleangetIsAtRiskOfHipDysplasia();
voidsetIsAtRiskOfHipDysplasia(boolean isAtRisk);
}
Because then you can do
publicclassGermanShepardextendsRealmObjectimplementsIGermanShepard{
privateint numLegs;
privateboolean hasFur;
privateString color;
privateboolean canDoTricks;
privateboolean isGuardDog;
privateboolean isAtRiskofHipDysplasia;
// inherited getters/setters
}
You can even make repository class out of it
publicabstractclassAnimalRepository<TextendsIAnimal> {
protected Class<T> clazz;
publicAnimalRepository(Class<T> clazz) {
this.clazz = clazz;
}
public RealmResults<T> findAll(Realm realm) {
return realm.where(clazz).findAll();
}
}
@Singleton
publicclassGermanShepardRepositoryextendsAnimalRepository<GermanShepard> {
@Inject
publicGermanShepardRepository() {
super(GermanShepard.class);
}
}
And then
@InjectGermanShepardRepository germanShepardRepository;
RealmResults<GermanShepard> results = germanShepardRepository.findAll(realm);
But you can indeed merge them into one class and then give it a String type;
parameter to know what type it originally was. That's probably even better than having all these GermanShepards.
Post a Comment for "Composition Over Inheritance For Realmobjects With Gson Serialization"