Singleton from library class

610 views Asked by At

I have a jar with a class inside it. I add a jar as a library to the project. Class is public and has a public constructor. It is necessary to ensure that class will be initialized in a single instance. How can I do it without changing the jar file?

1

There are 1 answers

0
Mike67 On

If the jar class is public with a public constructor, there's no way to block others from creating a new instance.

You can use a singleton wrapper class to make the public class less obvious:

public class MyClass extends JarClass {

    private static MyClass instance = new MyClass();

    private MyClass(){ super(); }  // create instance of jar class

    public static MyClass getInstance(){
        return instance;
    }
}