What
保證一個類只有一個實例,并提供它的全局唯一訪問點昧穿。
保證一個Class只有一個實體對象存在。
具體可以有很多種胃碾,只有保證全局唯一就可以
初始化就創(chuàng)建
public class Singleton {
private Singleton() {
}
private static Singleton instance = new Singleton();
public static Singleton getInstance()
{
return instance;
}
}
lazy load
當用的時候再創(chuàng)建雁佳。
public class SingletionLazy {
private SingletionLazy() {}
private static SingletionLazy instance = null;
public static synchronized SingletionLazy getInstance()
{
if(instance == null)
instance = new SingletionLazy();
return instance;
}
}
double check
兩次檢查null
public class Singleton{
private static Singleton singleton;
private Singleton (){}
public static Singleton getSingleton() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}