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
A
getInstance();
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
new B();
, A - , - :
class A { private static final A INSTANCE = new A(); private A() { } public static A getInstance() { return INSTANCE; } }
, A - - A -, - getInstance(), .
getInstance()
B B , B, .
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.
Source: https://habr.com/ru/post/1748951/More articles:How to preserve the identity of an object in different virtual machines - java"Interception" of user input in a text field and its removal - javascriptWord, download PDF using Rails - ruby-on-railsIE Mixed Warining Content Using https and http: 443 URLs? - internet-explorerCan I send an ESC d command to a POS printer from perl? - perlhttps://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1748952/google-maps-geocoding-address-to-glatlng&usg=ALkJrhjeLWN99wvlAVD7CLUHUDnOYxLEzQHow to filter a node list based on the contents of another node list - xsltHow to access DIV inside iframe from parent - javascriptHave you ever used these css properties? - cssiPhone4 960x640 - impact on apps? - iphoneAll Articles