饿汉式
public class EagerSingleton
{
private EagerSingleton()
{}
private static final EagerSingleton singletonInstance = new EagerSingleton();
public static EagerSingleton getInstance()
{
return singletonInstance;
}
}
懒汉式
public class LazySingleton
{
private LazySingleton()
{}
private static LazySingleton singletonInstance;
public static LazySingleton getInstance()
{
if(singletonInstance==null)
{
singletonInstance = new LazySingleton();
}
return singletonInstance;
}
}
主程序:
public class SingletonMain
{
public static void main(String[] args)
{
//EagerSingleton es = new EagerSingleton();
//LazySingleton ls = new LazySingleton();
EagerSingleton es2 = EagerSingleton.getInstance();
LazySingleton ls2 = LazySingleton.getInstance();
}
}
注意:
1.主程序中es和ls都无法实现,因为饿汉和懒汉的构造函数均为private。
2.懒汉式中的singletonInstance不能为final,因为定义时未赋值,而是请求实例时赋值,如为final则不可定义后更改其值。