如何使一個類只能夠有一個對象 呢,我們知道這樣的類的構造函數是必須為私有的,否則用戶就可以任意多的生產該類的對象了。那么具體應該怎么實現呢,有兩種方式:一種是給類一個該類型的 static 成員對象,每次都調用一個get方法返回該對象,這也就是所謂的餓漢模式;
public class EagerSingleton {
String name;
private static final EagerSingleton m_instance = new EagerSingleton();
private EagerSingleton()
{
name ="wqh";
}
public static EagerSingleton getInstance()
{
return m_instance;
}
public static void main(String[] args) {
EagerSingleton es ;
es = EagerSingleton.getInstance();
System.out.println(es.name);
}
}
在有一種呢就是在該類型里面先聲明一個對象,如何通過一個同步的static方法每次返回同一個 對象,這也就是 所謂的懶漢模式,如下:
public class LazySingleton {
private static LazySingleton m_instance = null;
private LazySingleton()
{
}
synchronized public static LazySingleton getInstance()
{
if(m_instance == null)
{
m_instance = new LazySingleton();
}
return m_instance;
}
public static void main(String[] args) {
LazySingleton ls;
ls = LazySingleton.getInstance();
System.out.println(ls.getClass());
}
}