繁体   English   中英

创建2个单例类Java实例

[英]create 2 instances of a singleton class Java

我知道这个问题很奇怪,但我只是想知道:有没有办法在Java中创建Singleton类的多个实例?

我的情况是这样的:

我有一个Singleton类,并且我需要该类的2个对象/实例。 有什么方法可以修改类以创建多个实例?

我的课:

public class SingletonClass {

    private static SingletonClass sSoleInstance;

    //private constructor.
    private SingletonClass(){

        //Prevent form the reflection api.
        if (sSoleInstance != null){
            throw new RuntimeException("Use getInstance() method to get the single instance of this class.");
        }
    } 

    public static SingletonClass getInstance(){
        if (sSoleInstance == null){ //if there is no instance available... create new one
            sSoleInstance = new SingletonClass();
        }

        return sSoleInstance;
    }
}

可以使用枚举模式创建单例。 喜欢

public enum Whatever { 
  INSTANCE;
}

将其变成Bi-Singleton就像:

public enum Whatever { 
  INSTANCE, YETANOTHER
}

记录一下:我刚写了“ bi-singleton”一词; 从概念上讲,这几乎意味着0。 如果您需要多个实例,则它不是单例。 期。 因此,您的问题听起来更像是XY问题。

请注意:考虑使用该枚举解决方案; 因为默认情况下它是线程安全的; 您正在使用的代码不是。 但是在进行更改之前,请进行一些研究以了解这些方法的利弊。

具有有效用例的绝对有效问题-简而言之,当使用静态工厂方法时,您可以具有一个带有私有构造函数的类的多个实例。 通过使构造函数私有化,可以确保您的类不能从外界实例化,但是与此同时,所讨论的类可以根据需要多次实例化自身。

请查看本文以获取详细信息和代码示例。 希望能有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM