java實現單例

將類的構造函數聲明爲private,只能在類內通過new Test()創建對象,在類內實現getInstance() 函數,實現new Test()創建對象。
下面爲實現代碼:

/**
 * @Description:Java實現單例
 * @author: 詩人的情人
 * @Date: 8:56 上午 2019/10/20
 */
public class JustForTest {
    public static void main(String[] args) {
        Test.getInstance().fun();
        Test.getInstance().fun();
    }
}

class Test{
    private volatile static Test instance;
    public static Test getInstance() {
        if (instance == null) {
            synchronized (Test.class) {
                if (instance == null) {
                    instance = new Test();
                }
            }
        }
        return instance;
    }
    private Test() {
        System.out.println("調用構造函數");
    }
    public static void fun() {
        System.out.println("調用fun");
    }
}

輸出:

調用構造函數
調用fun
調用fun

Process finished with exit code 0

從輸出結果可以看到:調用了兩次fun()函數,構造函數只調用了一次。

代碼很簡單,記錄一下自己的成長過程吧。

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