Creating an instance in java class

Please tell me the difference between the two ways of declaring a java constructor

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

and

    public class B{
    public B(){};


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

thank

+3
source share
3 answers
  • The class Ashould be Singleton , where you can have only one instance of A. You retrieve this single instance by callinggetInstance();

In singleton software development, a design pattern is a design pattern used to implement the mathematical concept of singleton, restricting the instantiation of an object class . This is useful when exactly one object is needed to coordinate actions in 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;
    }
}
  • B - . B, , new B();
+11

, A - , - :

class A {
 private static final A INSTANCE = new A();
 private A() { }
 public static A getInstance() { return INSTANCE; }
}

, A - - A -, - getInstance(), .

B B , B, .

+5

In the first case, only one instance is available. In the second case, you can have as much as possible. You must make the constructor closed in the first case.

0
source

Source: https://habr.com/ru/post/1748951/


All Articles