一、恶汉式
/**
* Created by yanbo on 2017/7/7.
* 恶汉试(类加载就初始化)
*/
public class Singleton {
public static Singleton instance = new Singleton();
public static Singleton getInstance(){
return instance;
}
}
二、懒汉式
/**
* Created by yanbo on 2017/7/7.
* 懒汉式(双重判断)
*/
public class Singleton2 {
public static Singleton2 instance;
public static Singleton2 getInstance(){
if (instance == null){
synchronized (Singleton2.class){
if (instance == null){
instance = new Singleton2();
}
}
}
return instance;
}
}
三、使用Java的枚举
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;
}
}