单例模式的使用大致分为两种:饿汉式和懒汉式
饿汉式:需要用的时候判断有没有,如果有就返回实例,如果没有就生成实例
public class Singleton {
//私有化构造函数,防止外界再生成其他实例
private Singleton(){
}
//定义实例,同样也是私有,防止通过类直接获取
private static Singleton instance;
//提供外部访问接口
public Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}
饿汉式看上去虽然很完美,但是在多线程环境下可能会产生多线程问题,慎用。
懒汉式:实例已经生成好,就等你来用了!
第一种:
public class Singleton {
//私有化构造函数,防止外界再生成其他实例
private Singleton() {
}
private static Singleton instance = new Singleton();
//提供外部访问接口
public static Singleton getInstance() {
return instance;
}
}
第二种:
public class Singleton {
private Singleton() {
}
// 此处使用一个内部类来维护单例
private static class SingletonFactory {
private static Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonFactory.instance;
}
}
上面两种懒汉式都是线程安全的,都是推荐的。
区别是第一种在jvm加载类的时候就new出了实例,第二种是调用的时候new出实例。所以如果instance较大或者加载时间较长的时候,还是推荐使用第二种懒汉式。
补充说下,单例模式的构造方法以及私有化了,所以上面介绍的单例模式的类是不能被继承的。