gpt4 book ai didi

java - 在java类中创建实例

转载 作者:搜寻专家 更新时间:2023-11-01 04:03:45 24 4
gpt4 key购买 nike

请告诉我两种java构造函数声明方式的区别

  public class A{

private static A instance = new A();
public static A getInstance() { return instance;
}
public static void main(String[] args) {
A a= A.getInstance();
}
}

    public class B{
public B(){};


public static void main(String[] args) {
B b= new B();
}
}

谢谢

最佳答案

  • A 应该是 Singleton ,其中您只能拥有 A 的一个实例。您可以通过调用 getInstance();
  • 检索该单个实例

In software engineering, the singleton pattern is a design pattern used to implement the mathematical concept of a singleton, by restricting the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.

根据您的要求,有几种方法可以解决此问题:

public class A{
private static A instance = new A();
private A(){} // private constructor
public static A getInstance() {return instance;}
}

或者直到第一次调用才创建实例

public class A{
private static A instance = null;
private A(){} // private constructor
public static A getInstance() {
if(instance == null){
instance = new A(); // create the one instance.
}
return instance;
}
}
  • Class B 是一个带有无参数构造函数的类。您可以通过调用 new B();
  • 创建任意数量的 B 实例

关于java - 在java类中创建实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2994418/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com