Java 如何为 Singleton 类创建多个实例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20786961/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 04:19:39  来源:igfitidea点击:

How to create multiple instances for Singleton class

javaobjectdesign-patternssingletoninstance

提问by mayooran

I have created a Singleton class using lazy initialization method. That is the getInstance method is synchronized. But without changing the design pattern is there a way to create multiple instances of the Singleton class. Because changing the Singleton pattern will take lot of architectural changes. Please advice a way to create multiple instances. Please help in Java.

我使用延迟初始化方法创建了一个单例类。那就是getInstance 方法是同步的。但是在不改变设计模式的情况下,有没有一种方法可以创建 Singleton 类的多个实例。因为改变单例模式需要很多架构上的改变。请建议一种创建多个实例的方法。请在 Java 中提供帮助。

采纳答案by PopoFibo

EDIT:I don't have the required reputation to add it as a comment hence adding it as an answer - as pointed out in the comments, it's a possible duplicate.

编辑:我没有将其添加为评论所需的声誉,因此将其添加为答案 - 正如评论中指出的那样,它可能是重复的。

A little research and there you have it:

一点研究,你就知道了:

Reference this link

参考这个链接

Code

代码

class MySingleton {
    private MySingleton() {
    }
}

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

回答by Aniket Thakur

Singleton patten means only one instance is allowed. So there is no question of creating multiple instances.

单例模式意味着只允许一个实例。所以不存在创建多个实例的问题。

Though there are some hacks and workarounds like Serializing the Object and De Serializingit back or using different Class loadersbut again it violates the basic principle why Singleton pattern is created for.

尽管有一些像Serializing the Object and De Serializing它一样的黑客和变通方法,using different Class loaders但它再次违反了创建单例模式的基本原则。

回答by Peter Lawrey

You want to have multiple instances of a class which can only have one instance by design.

您希望拥有一个类的多个实例,而设计上只能有一个实例。

You can, but it is no longer a singleton. Treat it as a normal object which have multiple instances and the restriction is lifted. How you do that depends on your use case.

你可以,但它不再是一个单身人士。将其视为具有多个实例的普通对象并解除限制。您如何做到这一点取决于您的用例。

回答by Juan Sánchez

It will depend on the class behaviour. If the instance is well encapsulated, you can recreate what getInstancemethod does using reflection, I guess.

这将取决于类的行为。如果实例封装得很好getInstance,我猜你可以重新创建使用反射的方法。