單例模式(Singleton Pattern)是 Java 中最簡單的設計模式之一。這種類型的設計模式屬於創建型模式
特點:
- 單例類只能有一個實例。
- 單例類必須自己創建自己的唯一實例。
- 單例類必須給所有其他對象提供這一實例
懶漢式:
package com.example;
/**
* 懶漢式
* 加鎖 synchronized線程安全
*/
public class Student {
private static Student student;
private Student(){};
public static synchronized Student getInstance(){
if (student == null) {
student = new Student();
}
return student;
}
public static void main(String[] args) {
Student student1 = Student.getInstance();
Student student2 = Student.getInstance();
if(student1 == student2){
System.out.println("同一個學生");
}else{
System.out.println("不是同一個學生");
}
}
}
輸出結果:
餓漢式:
package com.example;
/**
* 餓漢式
* 多線程安全
* 類加載時就初始化
*/
public class Student1 {
private static Student1 student1 = new Student1();
private Student1(){};
public static synchronized Student1 getInstance(){
return student1;
}
public static void main(String[] args) {
Student1 student1 = Student1.getInstance();
Student1 student2 = Student1.getInstance();
if(student1 == student2){
System.out.println("同一個學生");
}else{
System.out.println("不是同一個學生");
}
}
}
輸出結果:
雙重校驗鎖
package com.example;
/**
* 雙重校驗鎖
* 線程安全
*/
public class Student2 {
private volatile static Student2 student2;
private Student2 (){}
public static Student2 getInstance() {
if (student2 == null) {
synchronized (Student2.class) {
if (student2 == null) {
student2 = new Student2();
}
}
}
return student2;
}
public static void main(String[] args) {
Student2 student1 = Student2.getInstance();
Student2 student2 = Student2.getInstance();
if(student1 == student2){
System.out.println("同一個學生");
}else{
System.out.println("不是同一個學生");
}
}
}
輸出結果: