1 主要作用是保证在Java应用程序中,一个类Class只有一个实例存在。
一 :第一种 饿汉式(预加载)
1 public class Singleton { 2 private Singleton(){}////在自己内部定义自己一个实例,注意这是private 3 private static Singleton instance = new Singleton(); 4 5 public static Singleton getInstance() { 6 return instance; 7 } 8 9 public static void main(String[] args) { 10 Singleton sing=Singleton.getInstance(); 11 System.out.println(sing); 12 } 13 }
二:第二种 饿汗式(变种)
1 public class Singleton { 2 private Singleton (){} 3 private Singleton instance = null; 4 static { 5 instance = new Singleton(); 6 } 7 8 public static Singleton getInstance() { 9 return this.instance; 10 } 11 public static void main(String[] args) { 12 Singleton sing=Singleton.getInstance(); 13 System.out.println(sing); 14 } 15 }
三:第三种 懒汉式(懒加载 线程不安全)
1 public class Singleton { 2 private Singleton(){} 3 private static Singleton instance; 4 5 public static Singleton getInstance() { 6 if (instance == null) { 7 instance = new Singleton(); 8 } 9 return instance; 10 } 11 12 public static void main(String[] args) { 13 Singleton sing=Singleton.getInstance(); 14 System.out.println(sing); 15 } 16 }
四:第四种 懒汉式(单线程安全)
1 public class Singleton { 2 private Singleton(){} 3 private static Singleton instance; 4 5 public static synchronized Singleton getInstance() { 6 if (instance == null) { 7 instance = new Singleton(); 8 } 9 return instance; 10 } 11 12 public static void main(String[] args) { 13 Singleton sing=Singleton.getInstance(); 14 System.out.println(sing); 15 } 16 }
五:第五种 静态内部类
1 public class Singleton { 2 private Singleton (){} 3 private static class SingletonHolder { 4 private static final Singleton INSTANCE = new Singleton(); 5 } 6 7 public static final Singleton getInstance() { 8 return SingletonHolder.INSTANCE; 9 } 10 //因为SingletonHolder类没有被主动使用,只有显示通过调用getInstance方法时,才会显示装载SingletonHolder类,从而实例化instance。 11 12 }
六:第六种 双重校验锁
1 public class Singleton { 2 private volatile static Singleton instance=null; 3 private Singleton (){} 4 public static Singleton getInstance() { 5 if (instance== null) { 6 synchronized (Singleton.class) { 7 if (instance== null) { 8 instance= new Singleton(); 9 } 10 } 11 } 12 return instance; 13 } 14 }
这种方式只是在初始化Singleton那部分代码的时候添加同步锁,这样提高了效率。
时间: 2024-10-30 05:32:57