第一种:饱汉模式
public class SingleTon {
private SingleTon(){
}
//实例化放在静态代码块里可提高程序的执行效率,但也可能更占用空间
private final static SingleTon instance = new SingleTon();
public static SingleTon getInstance(){
return instance;
}
}
第二种:饥汉模式,
public class SingleTon {
private SingleTon(){}
private static instance = null;//new SingleTon();
public static synchronized SingleTon getInstance(){
if(instance == null)
instance = new SingleTon();
return instance;
}
}
第三种:用枚举
public enum SingleTon{
ONE;
} |