目前单例模式有三种形式

1、提供一个静态的公共属性
2、提供一个静态的公共方法
3、enum类型的(这个是针对jdk 1.5以及1.5版本以上的)

 

 
  
  1. package com.test;  
  2.  
  3. import java.lang.reflect.Constructor;  
  4. import java.lang.reflect.InvocationTargetException;  
  5.  
  6. enum SingletonExample {  
  7.     uniqueInstance;  
  8.     public static SingletonExample getInstance(){  
  9.         return uniqueInstance;  
  10.     }  
  11. }  
  12.  
  13. /**  
  14.  * 枚举单例测试  
  15.  * @author 乔磊  
  16.  *  
  17.  */ 
  18. public class EnumTest {  
  19.     public static void singletonTest() throws IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException{  
  20.         try {  
  21.             //得到第一个实例  
  22.             SingletonExample s = SingletonExample.getInstance();  
  23.             //用反射得到第二个实例,这里引用类的时候得写全路径,否则会报找不到类  
  24.             Class c = Class.forName("com.test.SingletonExample");  
  25.             //getDeclaredConstructors返回 Constructor 对象的一个数组,  
  26.             //这些对象反映此 Class 对象表示的类声明的所有构造方法。  
  27.             //它们是公共、保护、默认(包)访问和私有构造方法。  
  28.             //返回数组中的元素没有排序,也没有任何特定的顺序。  
  29.             //如果该类存在一个默认构造方法,则它包含在返回的数组中。  
  30.             //如果此 Class 对象表示一个接口、一个基本类型、一个数组类或 void,  
  31.             //则此方法返回一个长度为 0 的数组  
  32.             Constructor[] con = c.getDeclaredConstructors();  
  33.             Constructor conc = con[0];  
  34.             //setAccessible将此对象的 accessible 标志设置为指示的布尔值。  
  35.             //值为 true 则指示反射的对象在使用时应该取消 Java 语言访问检查。  
  36.             //值为 false 则指示反射的对象应该实施 Java 语言访问检查。  
  37.             conc.setAccessible(true);  
  38.             SingletonExample ss = (SingletonExample)conc.newInstance(null);  
  39.             System.out.println(s+"/"+ss);  
  40.             System.out.println(s==ss);  
  41.         } catch (ClassNotFoundException e) {  
  42.             e.printStackTrace();  
  43.         }  
  44.     }  
  45.     public static void main(String[] args) throws IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException {  
  46.         singletonTest();  
  47.     }  

 

结果如下

 
  
  1. Exception in thread "main" java.lang.IllegalArgumentException: Cannot reflectively create enum objects  
  2.     at java.lang.reflect.Constructor.newInstance(Constructor.java:492)  
  3.     at com.test.EnumTest.singletonTest(EnumTest.java:26)  
  4.     at com.test.EnumTest.main(EnumTest.java:34)  

从结果可以看出用enum的单例是最安全的,其它两种方式都可以用反射得到,大家可以用以上方法进行测试。