自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

面試官:說(shuō)說(shuō)對(duì)單例模式的理解,最后的枚舉實(shí)現(xiàn)我居然不知

開(kāi)發(fā) 前端
說(shuō)起單例模式(Singleton Pattern),想必大家都不不會(huì)陌生,它是 Java 中最簡(jiǎn)單的設(shè)計(jì)模式之一,屬于創(chuàng)建型模式的一種,它提供了一種創(chuàng)建對(duì)象的最佳方式。

 

[[335972]]

本文轉(zhuǎn)載自微信公眾號(hào)「Java極客技術(shù)」,作者鴨血粉絲 。轉(zhuǎn)載本文請(qǐng)聯(lián)系Java極客技術(shù)公眾號(hào)。

 一、介紹

說(shuō)起單例模式(Singleton Pattern),想必大家都不不會(huì)陌生,它是 Java 中最簡(jiǎn)單的設(shè)計(jì)模式之一,屬于創(chuàng)建型模式的一種,它提供了一種創(chuàng)建對(duì)象的最佳方式。

這種模式的意義在于保證一個(gè)類僅有一個(gè)實(shí)例,并提供一個(gè)訪問(wèn)它的全局訪問(wèn)點(diǎn),避免重復(fù)的創(chuàng)建對(duì)象,節(jié)省系統(tǒng)資源。

二、實(shí)現(xiàn)思路

創(chuàng)建一個(gè)類,將其默認(rèn)構(gòu)造方法私有化,使外界不能通過(guò)new Object來(lái)獲取對(duì)象實(shí)例,同時(shí)提供一個(gè)對(duì)外獲取對(duì)象唯一實(shí)例的方法。

例如,創(chuàng)建一個(gè)SingleObject,如下:

  1. public class SingleObject { 
  2.   
  3.    //創(chuàng)建 SingleObject 的一個(gè)對(duì)象 
  4.    private static SingleObject instance = new SingleObject(); 
  5.   
  6.    //讓構(gòu)造函數(shù)為 private,這樣該類就不會(huì)被實(shí)例化 
  7.    private SingleObject(){} 
  8.   
  9.    //獲取唯一可用的對(duì)象 
  10.    public static SingleObject getInstance(){ 
  11.       return instance; 
  12.    } 
  13.   
  14.    public void showMessage(){ 
  15.       System.out.println("Hello World!"); 
  16.    } 

從 singleton 類獲取唯一的對(duì)象

  1. public class SingletonPatternDemo { 
  2.    public static void main(String[] args) { 
  3.   
  4.       //不合法的構(gòu)造函數(shù) 
  5.       //編譯時(shí)錯(cuò)誤:構(gòu)造函數(shù) SingleObject() 是不可見(jiàn)的 
  6.       //SingleObject object = new SingleObject(); 
  7.   
  8.       //獲取唯一可用的對(duì)象 
  9.       SingleObject object = SingleObject.getInstance(); 
  10.   
  11.       //顯示消息 
  12.       object.showMessage(); 
  13.    } 

執(zhí)行程序,輸出結(jié)果:

  1. Hello World! 

三、單例模式的幾種實(shí)現(xiàn)方式

3.1、懶漢式,線程不安全(不推薦)

這種方式是最基本的實(shí)現(xiàn)方式,這種實(shí)現(xiàn)最大的問(wèn)題就是不支持多線程。因?yàn)闆](méi)有加鎖 synchronized,所以嚴(yán)格意義上它并不算單例模式。這種方式 lazy loading 很明顯,不要求線程安全,在多線程不能正常工作。

  1. public class Singleton {   
  2.  
  3.     private static Singleton instance;   
  4.      
  5.     private Singleton (){}   
  6.    
  7.     public static Singleton getInstance() { 
  8.         if (instance == null) {   
  9.             instance = new Singleton();   
  10.         }   
  11.         return instance;   
  12.     }   

3.2、懶漢式,線程安全(不推薦)

這種方式具備很好的 lazy loading,能夠在多線程中很好的工作,但是,效率很低,99% 情況下不需要同步。優(yōu)點(diǎn):第一次調(diào)用才初始化,避免內(nèi)存浪費(fèi)。缺點(diǎn):必須加鎖 synchronized 才能保證單例,但加鎖會(huì)影響效率。getInstance() 的性能對(duì)應(yīng)用程序不是很關(guān)鍵(該方法使用不太頻繁)。

  1. public class Singleton { 
  2.  
  3.     private static Singleton instance; 
  4.      
  5.     private Singleton (){} 
  6.      
  7.     public static synchronized Singleton getInstance() { 
  8.         if (instance == null) { 
  9.             instance = new Singleton(); 
  10.         } 
  11.         return instance; 
  12.     } 

3.3、餓漢式(推薦使用)

這種方式比較常用,但容易產(chǎn)生垃圾對(duì)象。優(yōu)點(diǎn):沒(méi)有加鎖,執(zhí)行效率會(huì)提高。缺點(diǎn):類加載時(shí)就初始化,浪費(fèi)內(nèi)存。它基于 classloader 機(jī)制避免了多線程的同步問(wèn)題,不過(guò),instance 在類裝載時(shí)就實(shí)例化,雖然導(dǎo)致類裝載的原因有很多種,在單例模式中大多數(shù)都是調(diào)用 getInstance 方法, 但是也不能確定有其他的方式(或者其他的靜態(tài)方法)導(dǎo)致類裝載,這時(shí)候初始化 instance 顯然沒(méi)有達(dá)到 lazy loading 的效果。

  1. public class Singleton { 
  2.  
  3.     private static Singleton instance = new Singleton(); 
  4.      
  5.     private Singleton (){} 
  6.      
  7.     public static Singleton getInstance() { 
  8.         return instance; 
  9.     } 

3.4、雙檢鎖/雙重校驗(yàn)鎖(推薦使用)

這種方式采用雙鎖機(jī)制,安全且在多線程情況下能保持高性能。getInstance() 的性能對(duì)應(yīng)用程序很關(guān)鍵。

  1. public class Singleton {   
  2.  
  3.     private volatile static Singleton singleton;   
  4.      
  5.     private Singleton (){}   
  6.      
  7.     public static Singleton getSingleton() {   
  8.         if (singleton == null) {   
  9.             synchronized (Singleton.class) {   
  10.                 if (singleton == null) {   
  11.                     singleton = new Singleton();   
  12.                 }   
  13.             }   
  14.         }   
  15.         return singleton;   
  16.     }   

3.5、靜態(tài)內(nèi)部類(推薦使用)

這種方式能達(dá)到雙檢鎖方式一樣的功效,對(duì)靜態(tài)域使用延遲初始化,但實(shí)現(xiàn)更簡(jiǎn)單。這種方式只適用于靜態(tài)域的情況,雙檢鎖方式可在實(shí)例域需要延遲初始化時(shí)使用。

  1. public class Singleton { 
  2.  
  3.     private static class SingletonHolder { 
  4.      
  5.         private static final Singleton INSTANCE = new Singleton(); 
  6.     } 
  7.      
  8.     private Singleton (){} 
  9.      
  10.     public static final Singleton getInstance() { 
  11.         return SingletonHolder.INSTANCE; 
  12.     } 

3.6、枚舉(推薦使用)

這種實(shí)現(xiàn)方式還沒(méi)有被廣泛采用,但這是實(shí)現(xiàn)單例模式的最佳方法。它更簡(jiǎn)潔,自動(dòng)支持序列化機(jī)制,絕對(duì)防止多次實(shí)例化。這種方式是 Effective Java 作者 Josh Bloch 提倡的方式,它不僅能避免多線程同步問(wèn)題,而且還自動(dòng)支持序列化機(jī)制,防止反序列化重新創(chuàng)建新的對(duì)象,絕對(duì)防止多次實(shí)例化。不過(guò),由于 JDK1.5 之后才加入 enum 特性,用這種方式寫(xiě)不免讓人感覺(jué)生疏,在實(shí)際工作中,也很少用。

  1. public enum Singleton {  
  2.  
  3.     INSTANCE;   
  4.      
  5.     public void doMethod() { 
  6.      
  7.     }   

四、應(yīng)用

單例模式在Java中的應(yīng)用也很多,例如Runtime就是一個(gè)典型的例子,源碼如下:

  1. public class Runtime { 
  2.      
  3.     private static Runtime currentRuntime = new Runtime(); 
  4.  
  5.     /** 
  6.      * Returns the runtime object associated with the current Java application. 
  7.      * Most of the methods of class <code>Runtime</code> are instance  
  8.      * methods and must be invoked with respect to the current runtime object.  
  9.      *  
  10.      * @return  the <code>Runtime</code> object associated with the current 
  11.      *          Java application. 
  12.      */ 
  13.     public static Runtime getRuntime() {  
  14.     return currentRuntime; 
  15.     } 
  16.  
  17.     /** Don't let anyone else instantiate this class */ 
  18.     private Runtime() {} 
  19.  
  20.     ... 

很清晰的看到,使用了餓漢式方式創(chuàng)建單例對(duì)象!

五、總結(jié)

一般情況下,不建議使用第 1 種和第 2 種懶漢方式,建議使用第 3 種餓漢方式。只有在要明確實(shí)現(xiàn) lazy loading 效果時(shí),才會(huì)使用第 5 種登記方式。如果涉及到反序列化創(chuàng)建對(duì)象時(shí),可以嘗試使用第 6 種枚舉方式。如果有其他特殊的需求,可以考慮使用第 4 種雙檢鎖方式。

 

責(zé)任編輯:武曉燕 來(lái)源: Java極客技術(shù)
相關(guān)推薦

2021-11-02 22:04:58

模式

2021-06-30 07:19:36

React事件機(jī)制

2021-10-29 09:40:21

設(shè)計(jì)模式軟件

2021-05-31 10:35:34

TCPWebSocket協(xié)議

2021-07-07 08:36:45

React應(yīng)用場(chǎng)景

2021-07-12 08:35:24

組件應(yīng)用場(chǎng)景

2021-06-07 09:41:48

NodeBuffer 網(wǎng)絡(luò)協(xié)議

2021-06-08 08:33:23

NodeStream數(shù)據(jù)

2021-09-13 09:23:52

TypeScript命名空間

2021-07-13 07:52:03

ReactHooks組件

2021-06-10 07:51:07

Node.js循環(huán)機(jī)制

2024-08-13 17:56:52

單例裝飾器模式

2021-06-03 08:14:01

NodeProcessJavaScript

2021-06-04 07:55:30

Node Fs 操作

2021-07-29 07:55:20

React Fiber架構(gòu)引擎

2021-07-19 07:55:24

Redux中間件原理

2021-05-20 08:34:03

CDN原理網(wǎng)絡(luò)

2021-08-09 07:47:40

Git面試版本

2021-11-25 10:18:42

RESTfulJava互聯(lián)網(wǎng)

2020-07-02 07:52:11

RedisHash映射
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)