Java: getInstance vs Static

后端 未结 6 899
清歌不尽
清歌不尽 2021-01-30 11:17

What is the purpose of getInstance() in Java?

During my research I keep reading that getInstance() helps achieve a Singleton design pattern (w

6条回答
  •  庸人自扰
    2021-01-30 11:48

    Static will not give you a singleton. Since there is no way of making a top-level class a singleton in Java, you have getInstance methods which will implement some logic to to be sure there is only one instance of a class.

    public class Singleton {
    
       private static Singleton singleton;
    
       private Singleton(){ }
    
       public static synchronized Singleton getInstance( ) {
          if (singleton == null)
              singleton=new Singleton();
          return singleton;
       }
    
    }
    

    Check out this top answer: Static Classes In Java

    The above code will allow only one instance to be created, and it's clean, however as of Java 1.6, it is better to create singleton's as such since it is slightly more elegant IMHO:

    public enum MyEnumSingleton {
        INSTANCE;
    
        // other useful methods here
    } 
    

    Source: http://www.vogella.com/tutorials/DesignPatternSingleton/article.html

提交回复
热议问题