How to deal with Singleton along with Serialization

后端 未结 9 1588
感情败类
感情败类 2020-12-04 13:06

Consider I have a Singleton class defined as follows.

public class MySingleton implements Serializable{
 private static MySingleton myInstance;

 private MyS         


        
9条回答
  •  情深已故
    2020-12-04 13:53

    The best way to do this is to use the enum singleton pattern:

    public enum MySingleton {
      INSTANCE;
    }
    

    This guarantees the singleton-ness of the object and provides serializability for you in such a way that you always get the same instance.

    More generally, you can provide a readResolve() method like so:

    protected Object readResolve() {
      return myInstance;
    }
    

提交回复
热议问题