Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

oop - Sharing Realm fields on Android

Realm on Android doesn't support model inheritance/polymorphism.

So is there any way to share fields on Android? We have 5 models that all share the same synchronization-related fields and code. We use inheritance in our current SQLite models; if we switch to Realm, is our only choice to duplicate the sync fields across each of the 5 model classes?

As a workaround, I'm thinking about having those classes implement a Syncable interface with getters and setters for the shared fields, which at least let me share sync functionality. Is there a better way?

To share sync functionality, my best guess is to make a static Synchronizer class and pass it Syncable model objects. Synchronizer methods will use the Syncable interface to operate directly on model objects' shared, sync-related fields and delegate operations on type-specific fields. Alternatively, I could provide each model object its own Synchronizer instance...

Trying to find the right way to work around the inheritance limitation is really stretching my OOP skills... help is appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you use Kotlin, sharing the fields via an interface becomes even more trivial:

interface PersonBase {
    var name: String?
    var salary: Int
}

Then

class Person: RealmObject(), PersonBase {
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...