2017-07-25 176 views
-11

我是一位有一年半經驗的java開發人員。 我的問題是:什麼是單身人士?似乎我從來沒有在我的項目中使用它(Java web,Spring引導)。 我只是不明白爲什麼和什麼時候應該使用單例。 對不起,請讓我解釋一下我的困惑。 一個簡單的單例類是這樣的:什麼是單身模式?爲什麼和什麼時候應該使用它?

class Singleton { 

    private static Singleton instance; 

    private Singleton(){ 
    } 

    public static Singleton getInstance(){ 
    if(instance=null){ 
     instance=new Singleton(); 
    } 

    return instance; 
    } 
    ........ 
} 

看起來沒有區別,當我想新的單身對象: 辛格爾頓S =新的Singleton();

回答

0

單例模式允許您控制可以實例化的單例類的實例數。它被用於許多用例。

經典的Java單例看起來就像您提到的一個非常重要的細節 - 非公共構造函數。

事實上,構造函數是不公開的(受保護或私有)將不會允許任何人如你所說創建單身的新實例:

Singleton singleton = new Singleton(); 

而這比只具有常規很大的區別類。

注意,這樣的實現不是線程安全的,因此你要麼想擁有它的線程安全的或者非延遲初始化如下:

  • 非延遲初始化

    public class Singleton { 
        private static Singleton instance = new Singleton(); 
    
        private Singleton(){ 
        } 
    
        public static Singleton getInstance(){ 
         return instance; 
        } 
    } 
    
  • 線程安全

    public class Singleton { 
        private static Singleton instance = null; 
    
        protected Singleton() { 
        } 
    
        public static Singleton getInstance() { 
         if (instance == null) { 
          synchronized (Singleton.class) { 
           if (instance == null) { 
            instance = new Singleton(); 
           } 
          } 
         } 
         return instance; 
        } 
    } 
    
+0

非常感謝。我注意到,一旦Singleton類被加載到JVM中(可能就像這個笑),唯一的一個單例類實例被創建。當我調用方法'getInstance'時,我總是得到唯一的實例。所以,我認爲這是單身模式的含義。再次感謝你。上帝保佑你! – epicGeek

相關問題