Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Parcelable model classes outside Android, with a Parcelable wrapper

I would like to create some model classes that implement Android's Parcelable interface, but I want the classes to be usable outside Android. I thought about implementing a wrapper for all these model classes (they are serialized in the same way, with Google Protocol Buffers internally), but I am not sure how to do it.

Say I have an interface Model, and an implementing class ModelImpl. Currently, Model extends Parcelable, but I would like to decouple Model and ModelImpl from Parcelable, and have a ParcelWrapper instead. Preferably, this should all be type safe and nice. Any pointers as to how to approach this problem?

If I come across a solution, I'll post it here, of course.

Thanks! :)

like image 613
Markus Avatar asked Sep 03 '25 17:09

Markus


1 Answers

I ended up using the decorator pattern. So now I've got:

  • Model, the interface that defines the public methods I need.
  • ModelImpl, the actual implementing model class (which uses Google Protocol Buffers for serialisation)
  • ModelParcelDecorator, which implements Model and Parcelable, and takes an instance of an implementation of Model and stores it as reference, delegating all methods from the Model interface to this instance. ModelParcelDecorator uses the protocol buffers serialisation mechanism directly, so I don't need to serialise into a Parcel and back manually.

Model and ModelImpl can now reside in their own library, and be used outside Android.

Unfortunately, I needed to write a decorator for each of my model classes, but this is the best solution I found until now. If I find something better, I will post it here.

like image 180
Markus Avatar answered Sep 05 '25 08:09

Markus