Java常用設計模式-單例模式(Singleton Pattern)

單例模式(Singleton Pattern)是 Java 中最簡單的設計模式之一。這種類型的設計模式屬於創建型模式

特點:

  1. 單例類只能有一個實例。
  2. 單例類必須自己創建自己的唯一實例。
  3. 單例類必須給所有其他對象提供這一實例

 懶漢式:

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("不是同一個學生");
        }
    }
}

輸出結果: 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章