Skip to content

Instantly share code, notes, and snippets.

@ericmaxwell2003
Last active September 25, 2017 21:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericmaxwell2003/6b579240901bb2c0c919476bc39e2a22 to your computer and use it in GitHub Desktop.
Save ericmaxwell2003/6b579240901bb2c0c919476bc39e2a22 to your computer and use it in GitHub Desktop.
Using composition over inheritance with Realm
interface Animal {
String getColor();
void setColor(String color);
int getLegCount();
void setLegCount(int legCount);
}
@RealmClass
public class AnimalEntity implements RealmModel, Animal {
private String color;
private int legCount;
@Override
public String getColor() {
return null;
}
@Override
public void setColor(String color) {
}
@Override
public int getLegCount() {
return 0;
}
@Override
public void setLegCount(int legCount) {
}
}
interface Cat extends Animal {
boolean isDeclawed();
void setDeclawed(boolean declawed);
}
@RealmClass
public class CatEntity implements RealmModel, Cat {
private boolean isDeclawed;
private AnimalEntity commonAttributes;
// In real app, need to check for null here when referencing commonAttributes.
@Override
public String getColor() { return commonAttributes.getColor(); }
@Override
public void setColor(String color) { commonAttributes.setColor(color); }
@Override
public int getLegCount() { return commonAttributes.getLegCount(); }
@Override
public void setLegCount(int legCount) { commonAttributes.setLegCount(legCount); }
@Override
public boolean isDeclawed() { return isDeclawed; }
@Override
public void setDeclawed(boolean declawed) { this.isDeclawed = declawed; }
}
interface Duck extends Animal {
String getBillType();
void setBillType(String billType);
}
@RealmClass
public class DuckEntity implements RealmModel, Duck {
private String billType;
private AnimalEntity commonAttributes;
// In real app, need to check for null here when referencing commonAttributes.
@Override
public String getColor() { return commonAttributes.getColor(); }
@Override
public void setColor(String color) { commonAttributes.setColor(color); }
@Override
public int getLegCount() { return commonAttributes.getLegCount(); }
@Override
public void setLegCount(int legCount) { commonAttributes.setLegCount(legCount); }
@Override
public String getBillType() { return billType;}
@Override
public void setBillType(String billType) { this.billType = billType; }
}
List<? extends Duck> ducks = db.where(DuckEntity.class).findAll();
for(Duck duck : ducks) {
System.out.println("A duck has " + duck.getLegCount() + " legs, and this one has a " + duck.getBillType() + " type bill");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment