Skip to main content
gamedev.net
🔒 Locked

Serializing a State (pattern) object

Started by DeusFacticius Apr 27, 2006 at 10:17 PM 2 replies 950+ views
Original Post
DeusFacticius
DeusFacticius
So I got a bit of dilemma here, wanted you guys' input on coming up w/ an elegant solution... I have objects which make use of the State pattern for their behavior. These objects are also made to be serializable. The problem arises in that through serialization the objects need to maintain some kind of reference to which state object they should use, however the state objects themselves should not be serialized, as they are singletons. Does this make sense? I've developed one or two solutions involving enums and proxy's, however none of them seem very elegant. Can anyone present a clean solution to this dilemma?
ApochPiQ
ApochPiQ
Have each state object expose a method like GetIdentificationString() or whatever; it will return a unique string that identifies that state object. When serializing your other objects, have them call the identifier method on their associated state object, and serialize that. Deserialization should ask each state object in turn if it "knows" the ID string that was stored; if so, that state object takes over.


At least, I think that's what you're asking... [wink]
DeusFacticius
DeusFacticius
Thats not a bad idea, it would take some work to implement in Java however. I'm using the Java Serialization API.

I could use the Class.getName() method on the State object and use that as its identifier, however the idea of iterating through the available State objects searching for match isn't appealing.

Maybe a Factory pattern would work well here? I'm not sure what kind of pattern would fit here.
Fred304
Fred304
Quote:
Original post by DeusFacticius
however the state objects themselves should not be serialized, as they are singletons.

That seems to be a common misunderstanding. Why shouldn't singletons be serializable?

Make the singleton serializable and add the following method:
protected Object readResolve(){    return singleton; // or whatever your static singleton is called}

Easy, huh?

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.