public
class Singleton{
//
訪問級別設置爲private,確保在系統的其餘代碼不會被實例化
private Singleton(){}
//
聲明static,在jvm加載單例類時,單例對象就會被創建
private
static Singleton singletion =
new Singleton();
public
static Singleton getInstance(){
return singleton;
}
}
public
class Singleton{
private Singleton(){}
private
static Singleton singleton =
null;
//
同步,防止多線程環境下建立多個實例
public
static
synchronized Singleton getInstance(){
if(singleton ==
null){
singleton =
new Singleton();
}
return singleton;
}
}
//當Singleton加載時,不會初始化其內部類;只有在調用getInstance這個方法時,纔會加載內部類SingletonHolder,實現了延遲加載的功能,又下降系統性能。
public
class Singleton{
private Singleton(){}
private
static
class SingletonHolder{
private
static Singleton instance =
new Singleton();
}
public
static Singleton getInstance(){
return SingletonHolder.instance; } }