Junior — Middle
How can the process of converting a Singleton object to a serialized format and back be implemented?
sobes.tech AI
Answer from AI
To serialize and deserialize a Singleton object in Android (or Java), you need to ensure that during deserialization, a new instance is not created, but the existing Singleton instance is returned.
Main steps:
- The Singleton class should implement the
Serializableinterface. - In the class, define the
readResolve()method, which returns the existing Singleton instance during deserialization.
Example:
public class MySingleton implements Serializable {
private static final long serialVersionUID = 1L;
private static final MySingleton INSTANCE = new MySingleton();
private MySingleton() {
// private constructor
}
public static MySingleton getInstance() {
return INSTANCE;
}
// Method that ensures the same instance is returned upon deserialization
private Object readResolve() throws ObjectStreamException {
return INSTANCE;
}
}
Thus, during serialization, the object is saved, and during deserialization, readResolve() returns the existing instance, maintaining the Singleton pattern.