本帖最后由 杨文宇 于 2012-8-5 14:20 编辑
- enum SingletonExample {
- INSTANCE;
- public static SingletonExample getInstance(){
- return INSTANCE;
- }
- }
- class Singleton{
- private static Singleton instance = new Singleton();
- private Singleton(){}
- public static Singleton getInstance() {
- return instance;
- }
- }
- public class EnumTest {
- public static void singletonTest() throws IllegalArgumentException, InstantiationException,
- IllegalAccessException, InvocationTargetException{
- try {
- /*//枚举
- * SingletonExample s = SingletonExample.getInstance();
- Class c = Class.forName("javaEnhance.SingletonExample");
- */
- //单例
- Singleton s = Singleton.getInstance();
- Class c = Class.forName("javaEnhance.Singleton");
- Constructor[] con = c.getDeclaredConstructors();
- Constructor conc = con[0];
- //值为 true 则指示反射的对象在使用时应该取消 Java 语言访问检查。
- conc.setAccessible(true);
- //创建枚举实例
- // SingletonExample ss = (SingletonExample)conc.newInstance();
- //创建饿汉式单例
- Singleton ss = (Singleton)conc.newInstance();
- System.out.println(s+"="+ss);
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- }
- }
- public static void main(String[] args) throws IllegalArgumentException,
- InstantiationException, IllegalAccessException, InvocationTargetException {
- singletonTest();
- }
- }
复制代码 上面使用暴力反射可以强行把饿汉式单例实例化,而无法将枚举实例化;
所以,使用枚举做单例比普通单例更安全,功能更强大(因为提供了更多方法。)
|