英文:
Singleton from library class
问题
我有一个里面包含一个类的 JAR 文件。我将一个 JAR 文件添加为项目的库。这个类是公共的并且有一个公共构造函数。需要确保该类在单一实例中被初始化。如何在不更改 JAR 文件的情况下实现这一点?
英文:
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
得分: 1
如果JAR类是公共的,具有公共构造函数,就没有办法阻止其他人创建新实例。
您可以使用单例包装类使公共类不那么明显:
public class MyClass extends JarClass {
private static MyClass instance = new MyClass();
private MyClass(){ super(); } // 创建JAR类的实例
public static MyClass getInstance(){
return instance;
}
}
英文:
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;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论