单例模式来自库类

huangapple go评论66阅读模式
英文:

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;
    }
}

huangapple
  • 本文由 发表于 2020年9月29日 23:48:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/64123138.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定