Java深入探索單例模式的應用
1.單例
1.所謂類的單例設計模式,就是采取一定的方法保證在整個的軟件系統中,對某個類只能存在一個對象實例,并且該類只提供一個取得其對象實例的方法。
2.單例設計模式有兩種方式:
1)餓漢式。
2)懶漢式
2.單例設計模式的應用實例
1.步驟
1)構造器私有化=》防止用戶直接new出一個對象
2)類的內部創(chuàng)建對象
3)向外暴露一個靜態(tài)的公共方法。
4)代碼實現
2.單例模式-餓漢式
package com.demo.single_; public class test01 { public static void main(String[] args) { // girlfriend g01=new girlfriend("小紅"); // girlfriend g01=new girlfriend("下華"); girlfriend t01=girlfriend.getInstance(); System.out.println(t01); girlfriend t02=girlfriend.getInstance(); System.out.println(t02); if(t01==t02) System.out.println("true"); } } //有一個類,girlfriend //只能有一個girlfriend class girlfriend{ private String name; //1.構造器私有化 private girlfriend(String name){ this.name=name; } // 2.在類的內部直接創(chuàng)建 private static girlfriend g=new girlfriend("小紅"); //提供一個公共的static方法,返回對象g public static girlfriend getInstance(){ return g; } @Override public String toString() { return "girlfriend{" + "name='" + name + '\'' + '}'; } }
測試結果
注:單例設計模式中的對象通常是重量級的對象,餓漢式可能造成創(chuàng)建了對象,但是沒有使用
3.單例模式-懶漢式
package com.demo.single_; //演示懶漢式的單例模式 public class test02 { public static void main(String[] args) { //new cat("大飛");錯誤。 System.out.println(cat.n); cat instence=cat.getInstance(); System.out.println(instence); //再次執(zhí)行,依然是大黃,cat.getInstance()中的if語句不再執(zhí)行 cat instence2=cat.getInstance(); System.out.println(instence2); } } //希望在程序運行過程中,,只能創(chuàng)建一個cat對象 //使用單例模式 class cat{ private String name; //1,將構造器私有化 private cat(String name) { System.out.println("構造器被調用"); this.name = name; } //2,定義一個靜態(tài)屬性對象 private static cat c1; public static int n=999; //3,提供一個public的static方法,可以返回一個cat對象 public static cat getInstance(){ if(c1==null){ c1=new cat("大黃"); } return c1; } @Override public String toString() { return "cat{" + "name='" + name + '\'' + '}'; } } //4,總結:只有當用戶使用getInstence()時,才返回cat c1對象, // 當后面再次調用時,會返回上次創(chuàng)建的對象
測試結果
3.餓漢式與懶漢式的區(qū)別
單例設計模式。
•餓漢式VS懶漢式
1.二者最主要的區(qū)別在于創(chuàng)建對象的時機不同:餓漢式是在類加載就創(chuàng)建了對象實例,
而懶漢式是在使用時才創(chuàng)建。
2.餓漢式不存在線程安全問題,懶漢式存在線程安全問題。
3.餓漢式存在浪費資源的可能。因為如果程序員一個對象實例都沒有使用,那么餓漢
式創(chuàng)建的對象就浪費了,懶漢式是使用時才創(chuàng)建,就不存在這個問題。
4.在我們javaSE標準類中,java.lang.Runtime就是經典的單例模式。
到此這篇關于Java深入探索單例模式的應用的文章就介紹到這了,更多相關Java單例模式內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringBoot @PropertySource與@ImportResource有什么區(qū)別
這篇文章主要介紹了SpringBoot @PropertySource與@ImportResource有什么區(qū)別,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習吧2023-01-01