在 java 中创建 main class 的静态单例是不是不好的编程习惯?

Is it bad programming practice to create a static singelton of main class in java?

我正在考虑使用 Singelton 设计模式并为我的 Main class 创建一个 Singelton。在搜索时,我发现一些评论认为这是相当糟糕的编程实践,特别是因为静态方法的声明不适合面向对象的编程。您对改进我的代码有什么建议吗?

public class MainClass {
private static MainClass instance = new MainClass();

public static MainClass getMainInstance() {
    return instance;
}

public static void main(String[] args) {
    MainClass main = Main.instance;
}
}

首先对于在class上实现的单例对象必须包括以下内容。

  1. it Should have all the constructor marked private.
  2. it should have the static method having the logic to create the object exactly only one time.
  3. it should have the static reference class variable to hold the single possible instance.

有了这些我们就可以保证Singleton对象,但这不是唯一的方法,我们可以有创建型设计模式或者Fly weight设计模式来克服静态方法调用。

Regarding Static keyword, it is still using the Class instance of a object. As we all know any object have the equivalent Singleton class object that gets created on the heap during class loading process. So it is not out of OOPS.

希望对您有所帮助!!!

虽然使用设计模式通常有助于清洁编程,但在没有必要的情况下过度使用它们会导致代码过于复杂。

如果你想为你的应用程序创建一个单例,声明一个 class 或更好的枚举会更有益,其中包含将由你的主要功能 运行 的应用程序。

使用枚举:

public enum Application{
    instance;

    public void run(){
    //do awesome stuff
    }
}

这会导致即使通过序列化也无法复制应用程序,而且您也无法使用接口来概括您的应用程序。

当使用普通 class 实现单例时,您需要将构造函数设为私有或保护 class 以防再次实例化。

使用带有私有构造函数的普通 class:

public class Application{
    private static final Application instance = new Application();

    private Application(){}

    public Application getApplication(){
        return instance;
    }

    public void run(){
    //do awesome stuff
    }
}

此变体的优点是 class 仍然可以实现接口或扩展 classes,例如可运行。 缺点是通过使用序列化 class 仍然可以多次实例化。