java單例設計模式學習
餓漢式和懶漢式的區別
- 1,餓漢式是空間換時間,懶漢式是時間換空間
- 2,在多線程訪問時,餓漢式不會創建多個對象,而懶漢式有可能會創建多個對象
-
懶漢模式
class Singleton { //1,私有構造方法,其他類不能訪問該構造方法了 private Singleton(){} //2,聲明一個引用 private static Singleton s ; //3,對外提供公共的訪問方法 public static Singleton getInstance() { //獲取實例 if(s == null) { //線程1等待,線程2等待 s = new Singleton(); } return s; }
# 餓漢模式
class Singleton {
//1,私有構造方法,其他類不能訪問該構造方法了
private Singleton(){}
//2,創建本類對象
private static Singleton s = new Singleton();
//3,對外提供公共的訪問方法
public static Singleton getInstance() { //獲取實例
return s;
}
# 第三種:
class Singleton1 {
//1,私有構造方法,其他類不能訪問該構造方法了
private Singleton1(){}
//2,聲明一個引用
public static final Singleton1 s = new Singleton1();
}
public static void main(String[] args) {
//Singleton s1 =new Singleton();
Singleton1 s1 = Singleton1.s;
Singleton1 s2 = Singleton1.s;
System.out.println(s1 == s2);
}
# 整合
package com.heima.thread;
public class Demo1_Singleton {
/** * @param args * * 單例設計模式:保證類在內存中只有一個對象。 */ public static void main(String[] args) { //Singleton s1 = new Singleton(); Singleton s1 = Singleton.s; //成員變量被私有,不能通過類名.調用 //Singleton.s = null; Singleton s2 = Singleton.s; System.out.println(s1 == s2); /* Singleton s1 = Singleton.getInstance(); Singleton s2 = Singleton.getInstance(); System.out.println(s1 == s2);*/ }
}
/*
- 餓漢式
class Singleton {
//1,私有構造方法,其他類不能訪問該構造方法了
private Singleton(){}
//2,創建本類對象
private static Singleton s = new Singleton();
//3,對外提供公共的訪問方法
public static Singleton getInstance() { //獲取實例
return s;
}
}/
/
-
懶漢式,單例的延遲加載模式
/
/class Singleton {
//1,私有構造方法,其他類不能訪問該構造方法了
private Singleton(){}
//2,聲明一個引用
private static Singleton s ;
//3,對外提供公共的訪問方法
public static Singleton getInstance() { //獲取實例
if(s == null) {
//線程1等待,線程2等待
s = new Singleton();
}return s;
}
}/
/ - 餓漢式和懶漢式的區別
- 1,餓漢式是空間換時間,懶漢式是時間換空間
- 2,在多線程訪問時,餓漢式不會創建多個對象,而懶漢式有可能會創建多個對象
*/
class Singleton {
//1,私有構造方法,其他類不能訪問該構造方法了
private Singleton(){}
//2,聲明一個引用
public static final Singleton s = new Singleton();
}
java單例設計模式學習