JAVA設計模式(第一種單例模式)

單例模式:
單例模式是設計模式中最簡單的模式之一,其中由(餓漢式單例模式、懶漢式單例模式······【就敲了這兩個,還有別的··】)
餓漢式單例模式;靜態對象,在聲明時創建。(在類被加載的時候創建其對象)
懶漢式單例模式;又稱爲延遲加載。
對比;懶漢式更消耗內存時間,餓漢式更消耗運行時間。
懶漢式單例模式:

package Danlimoshi;

public class Lanhanmoshi
{
    private static volatile Lanhanmoshi instance=null;
    private Lanhanmoshi(){}    
    public static synchronized Lanhanmoshi getInstance()
    {
        if(instance==null)
        {
            instance=new Lanhanmoshi();
        }
        return instance;
    }
}

餓漢單例模式:

package Danlimoshi;

public class Ehanmoshi
{
    private static final Ehanmoshi instance=new Ehanmoshi();
    private Ehanmoshi(){}
    public static Ehanmoshi getInstance()
    {
        return instance;
    }
}
public class Student {
    static Student student = new Student();
    //私有化構造方法,使得無法使用new來創建對象
    private Student() {
    }
    public static Student getInstanceOfStudent() {
        if (student == null)
            student = new Student();
        return student;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章