Java Singleton Design Pattern : Questions

后端 未结 11 834
渐次进展
渐次进展 2021-01-30 11:39

I had an interview recently and he asked me about Singleton Design Patterns about how are they implemented and I told him that using static variables and static methods we can i

11条回答
  •  忘掉有多难
    2021-01-30 12:22

    The Following Code is from here

    The Key point is you should Override the clone method...The Wikipedia example also is helpful.

    public class SingletonObject
    {
      private SingletonObject()
      {
        // no code req'd
      }
    
      public static SingletonObject getSingletonObject()
      {
        if (ref == null)
            // it's ok, we can call this constructor
            ref = new SingletonObject();        
        return ref;
      }
    
      public Object clone()
        throws CloneNotSupportedException
      {
        throw new CloneNotSupportedException(); 
        // that'll teach 'em
      }
    
      private static SingletonObject ref;
    }
    

提交回复
热议问题