(只适合单线程)
public class Singleton{
  private Singleton instance=null;
  private Singleton(){
  }
  public static Singleton getSingleton(){
    if(instance == null){
    instance = new Single();
    }
      return instance;
  }
}
(懒汉式单例 ->加了同步锁,适用于多线程 ---->   从而产生的问题是:
耗费时间,因为获取锁的过程很耗时)
public class Singleton{
  private Singleton instance=null;
  private Singleton(){
  }
  public static synchronized Singleton getSingleton(){
    if(instance == null){
      instance = new Single();
    }
    return instance;
  }
}

(懒汉式的优化-->只有当instance == null 是才会加同步锁,去创建实例)
public class Singleton{
  private Singleton instance=null;
  private Singleton(){
  }
  public static Singleton getSingleton(){
    if(instance == null){
      synchronized(Singleton.class){
        if(instance == null){
          instance = new Single();
        }
      }
    }
    return instance;
  }
}

(饿汉式:建议适用-->使用了静态属性-在类加载的时候就被创建,且只被创建一次)
public class Singleton{
  private static Singleton instance = new Singleton();
  private Singleton(){
  }
  public static Singleton getInsance(){
    return instance;
  }
}

(静态内部类:不怎么理解)
public class Singleton{
  private Singleton(){
  }
  private static class SingletonHolder{
    private final static instance= new Singleton();
  }
  public static Singleton getInsance(){
    return SingletonHolder.instacne;
  }
}

  

(只适合单线程)

public class Singleton{

private Singleton instance=null;

private Singleton(){

}

public static Singleton getSingleton(){

if(instance == null){

instance = new Single();

}

return instance;

}

}

(懒汉式单例 ->加了同步锁,适用于多线程 ---->   从而产生的问题是:

耗费时间,因为获取锁的过程很耗时)

public class Singleton{

private Singleton instance=null;

private Singleton(){

}

public static synchronized Singleton getSingleton(){

if(instance == null){

instance = new Single();

}

return instance;

}

}

 

(懒汉式的优化-->只有当instance == null 是才会加同步锁,去创建实例)

public class Singleton{

private Singleton instance=null;

private Singleton(){

}

public static Singleton getSingleton(){

if(instance == null){

synchronized(Singleton.class){

if(instance == null){

instance = new Single();

}

}

}

return instance;

}

}

 

(饿汉式:建议适用-->使用了静态属性-在类加载的时候就被创建,且只被创建一次)

public class Singleton{

private static Singleton instance = new Singleton();

private Singleton(){

}

public static Singleton getInsance(){

return instance;

}

}

 

(静态内部类:不怎么理解)

public class Singleton{

private Singleton(){

}

private static class SingletonHolder{

private final static instance= new Singleton();

}

public static Singleton getInsance(){

return SingletonHolder.instacne;

}

}