天天看点

枚举类型的单例模式

目前单例模式有三种形式

1、提供一个静态的公共属性

2、提供一个静态的公共方法

3、enum类型的(这个是针对jdk 1.5以及1.5版本以上的)

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

继续阅读