开发者

Transparently storing class state without exposing implementation

I have a model (MVC) class whose internal state (which basically contains of private int fields) I want to store.

The program is running on Android (for now) so I need to store the in a Bundle, but I开发者_如何学编程'll be using the same class later in a desktop application where I'll have to store the state some other way, so I can't reference Bundle directly in my class.

So my question is: What is the best way to store (and retrieve) the state of a class without exposing it's implementation?

The best I could think of removing the private access modifier so that the fields become package accessible and create read/write helper classes in the same package, but that somehow seems wrong.


I'm not familiar with the persistence mechanisms on Android, but in general, it's a good idea to separate your persistence logic (i.e. the code that stores objects' state) from the domain objects that actually contain the data. That's the approach taken by JPA and virtually all modern object-relational mapping tools in Java, for example. So yes, referencing Bundle objects directly in your domain classes doesn't sound like the right strategy, especially if you plan to use the same classes in a non-Android environment, too.

My advice is to serialize the object state into XML, which is portable across environments. There are lots of open source tools available that help make this easy and don't require any special code in your domain classes. The two I'm most familiar with are JiBX and Castor. I don't know if either will work on Android, but even if Android has its own tools to transform objects to and from XML, you still might be able to use JiBX or Castor on the desktop side, since they can adapt to many different XML formats.

Once you have the data in XML form, you can persist it using whatever means is most appropriate on the target environment. On the desktop app, that probably means files in the user's home directory. On Android, I guess it would be bundles, but that's not my area of expertise. Good luck!


Take a look at the bridge pattern, as well: http://en.wikipedia.org/wiki/Bridge_pattern As Rob said, you need to decouple the persistence from the data objects, so you can handle data uniformly and use a bridge to handle the persistence in different platforms.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜