使用java Reflection机制使单例模式不再只有一个对象的实例

在java的单例模式中,有几个要点。第一,构造方法私有,防止其它应用程序调用构造方法来创建对象;第二,有一个static的对象存放全局性变量,有一个getInstance方法来返回全局性变量,常见代码如下:

public class FactoryImpl  {
    private final static AtomicInteger count = new AtomicInteger(0);
    private final static  FactoryImpl INSTANCE = new FactoryImpl();
    private int id;

    private FactoryImpl() {
        id = count.incrementAndGet();
    }

    public int getId() {
        return id;
    }

    public static FactoryImpl getInstance() {
        return INSTANCE;
    }
}
但是我们还可以通用java Reflection机制调用类的构造方法,来创建多个对象,测试代码如下:
import java.lang.reflect.Constructor;

public class FactoryImplTest {
    private static final Class<?>[] EMPTY_ARRAY = new Class[] {};

    public static <T> T newInstance(Class<T> theClass) {
        T result;
        try {
            Constructor<T> meth = theClass.getDeclaredConstructor(EMPTY_ARRAY);
            meth.setAccessible(true);
            result = meth.newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return result;
    }
    
    public static void main(String[] args) {
        FactoryImpl impl1 = FactoryImpl.getInstance();
        System.out.println("impl1.getId: "  + impl1.getId());
        FactoryImpl impl2 = FactoryImpl.getInstance();
        System.out.println("impl2.getId: "  + impl2.getId());
        FactoryImpl impl3 = newInstance(FactoryImpl.class);
        System.out.println("impl3.getId: "  + impl3.getId());
        FactoryImpl impl4 = newInstance(FactoryImpl.class);
        System.out.println("impl4.getId: "  + impl4.getId());
    }
}

输出结果:

impl1.getId: 1
impl2.getId: 1
impl3.getId: 2
impl4.getId: 3

这说明impl1和impl2对象是一个,但impl3和impl4是用java Reflection机制构造的不同的对象。


你可能感兴趣的:(使用java Reflection机制使单例模式不再只有一个对象的实例)