單例模式即使沒有調用方法,對象也是可能被實例化的

一般的單例模式,都會把類的構造方法私有化以及構造出一個靜態對象,然後提供一個公有的獲取對象的方法,返回這個對象實例。

以下是最簡單的一種單例模式demo:

public class ASingleton {

    private ASingleton() {
        System.out.println("ASingleton構造方法被調用");
    }

    private static ASingleton instance = new ASingleton();

    public static ASingleton getInstance() {
        return instance;
    }

    public static void main(String[] args) {
        ASingleton.getInstance();
    }
}

運行main方法,結果如下:
在這裏插入圖片描述
不過也不是隻調用getInstance()方法時,纔會調用類的構造方法,當類中有字段被引用時,構造方法一樣會被調用

以下是帶有屬性的一種單例模式demo:

public class ASingleton {
    public static int NUMBER = 1;

    private ASingleton() {
        System.out.println("ASingleton構造方法被調用");
    }

    private static ASingleton instance = new ASingleton();

    public static ASingleton getInstance() {
        return instance;
    }

    public static void main(String[] args) {
        int number = ASingleton.NUMBER;
        System.out.println(number);
    }
}

運行main方法,結果如下:
在這裏插入圖片描述

總結

可以發現在單例模式中,當類中有字段被引用時,構造方法一樣會被調用。

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