如何多次实例化一个Singleton? [英] How to instantiate a Singleton multiple times?

查看:65
本文介绍了如何多次实例化一个Singleton?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码中需要一个单例.我用Java实现了它,并且效果很好.我这样做的原因是为了确保在多种环境中只有一个此类的实例.

I need a singleton in my code. I implemented it in Java and it works well. The reason I did it, is to ensure that in a mulitple environment, there is only one instance of this class.

但是现在我想使用单元测试在本地测试我的Singleton对象.因此,我需要模拟此Singleton的另一个实例(该对象可能来自另一个设备).那么是否有可能第二次实例化Singleton以进行测试,还是我必须对其进行模拟?

But now I want to test my Singleton object locally with a Unit test. For this reason I need to simulate another instance of this Singleton (the object that would be from another device). So is there a possiblity to instantiate a Singleton a second time for testing purpose or do I have to mock it?

我不确定,但是我认为可以通过使用其他类加载器来实现?

I'm not sure, but I think it could be possible by using a different class loader?

推荐答案

您可以使用反射调用单例类的私有构造函数,以创建该类的新实例.

You can invoke the private constructor of your singleton class using reflection to create a new instance of the class.

class MySingleton {
    private MySingleton() {
    }
}

class Test {
    public void test() throws Exception {
        Constructor<MySingleton> constructor = MySingleton.class.getConstructor();
        constructor.setAccessible(true);
        MySingleton otherSingleton = constructor.newInstance();
    }
}

这篇关于如何多次实例化一个Singleton?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆