首页 > 代码库 > 单例模式

单例模式

//单例模式的三个条件
//1.构造器私有的
//2.在自己内部定义自己一个实例,注意是private的,只供内部调用
//3.对外提供一个static方法,获取当前类的对象

public class Singleton {
  //懒汉模式,线程不安全
  private Singleton(){}
  private static Singleton instance;
  public static Singleton getInstance(){
    if(instance == null){
      instance = new Singleton();
    }
    return instance;
  }
}

//懒汉模式,线程安全,但多线程时效率很低
class Singleton2{
  private Singleton2(){}
  private static Singleton2 instance;
  public static synchronized Singleton2 getInstance(){
    if(instance==null){
      instance = new Singleton2();
    }
    return instance;
  }
}
//饿汉模式
class Singleton3{
  private Singleton3(){}
  private static Singleton3 instance = new Singleton3();
  public static Singleton3 getInstance(){
    return instance;
  }
}