Is it safe by default, like Java's 开发者_JAVA技巧single-element-enum pattern or is it e. g. necessary to define readResolve
or similar methods somewhere to prevent accidental or malicious breakage of the singleton contract?
Yes, it is safe by default:
object Singleton extends Serializable
// with Scala 2.8: @serializable object Singleton
import java.io._
val out = new ObjectOutputStream(new FileOutputStream("singleton"))
out.writeObject(Singleton)
out.close
val in = new ObjectInputStream(new FileInputStream("singleton"))
val obj = in.readObject
in.close
obj == Singleton // should print true
When you compile the object with scalac and decompile it (for example with JAD) you will get following Java-file:
public final class Singleton$ implements Serializable, ScalaObject
{
public Object readResolve()
{
return MODULE$;
}
private Singleton$()
{
}
public static final Singleton$ MODULE$ = new Singleton$1();
}
精彩评论