继续继续。
我鸿洋大神的博客
这里写链接内容
恶汉模式
在类加载的时候就初始化
public class Singleton {
private static Singleton instance = new Singleton();
public static Singleton getInstance()
{
return instance;
}
}
懒汉模式,需要双重判断的
public class Singleton02
{
private static Singleton02 instance;
public static Singleton02 getInstance()
{
if (instance == null)
{
synchronized (Singleton02.class)
{
if (instance == null)
{
instance = new Singleton02();
}
}
}
return instance;
}
}
使用Java的枚举,还是很推荐的,简单的跟神马一样,如果对枚举不熟悉,小google一下
public enum Singleton03
{
INSTANCE;
}
使用一个持有类,主要是为了不在初始化的时候加载
public class Singleton04
{
private static final class InstanceHolder
{
private static Singleton04 INSTANCE = new Singleton04();
}
public static Singleton04 getInstance()
{
return InstanceHolder.INSTANCE;
}
}
好了,就这么多,以上4种都是比较推荐使用的,除了第一种会类加载的时候初始化,其他3中都不会,且4种都保证线程安全,特殊情况(除了多个类加载器,和你非要通过反射等手段生成多个对象)不考虑。