Learning Java for more than a year, a lot of basic knowledge is understood, some know how to use, but do not understand, it is how to come.
Often in the book to see the introduction class inside the construction method, static methods, common methods and static variables, call order, but do not understand its true usefulness.
When I came into the company today, I suddenly thought of the Java class, the method, the variable call order is important, I think of a singleton mode, because I just know the usefulness of the singleton mode, but do not understand how it comes, the singleton mode is not based on the class start sequence is written out, because the class will first call static, Then, the constructor, it can be seen that some knowledge points, as long as you are flexible, it is of great use, of course, I do not know, people think my point is right, I think so.
Package com.fanshe;
public class Testb {
public static void Main (string[] args) {
TestA tmp = Testa.getsingleton ();
Tmp. Show ("Testb Call Show");
Tmp.setx (20);
System.out.println (Tmp.getx ());
TESTC TMPC = new TESTC ();
TMPC. Td ();
}
}
Static and static methods are called first, and then the construction method
Package com.fanshe;
public class TestA {
private static TestA Singleton = null;
int x;
Public TestA () {
x = 15;
System.out.println ("Enter construction method ...");
}
public static TestA Getsingleton () {
System.out.println ("Singleton =" +singleton);
if (Singleton = = null) {
System.out.println ("into a single case ...");
Singleton = new TestA ();
}
return Singleton;
}
public void Show (String str)
{
System.out.println (str);
}
public int GetX () {
return x;
}
public void SetX (int x) {
this.x = x;
}
}
Package com.fanshe;
public class TESTC {
public void Td ()
{
Testa.getsingleton (). Show ("TESTC Call Show");
System.out.println (Testa.getsingleton (). GetX ());
}
}
The results are as follows:
Singleton = null
Enter a single case ...
Enter Construction method ...
TESTB Call Show
20
Singleton = [email protected]
TESTC Call Show
Singleton = [email protected]
20
Singleton pattern determined by the order of call of the Java class