The so-called single-state, is called the class template created by the object is the same object. Like a TV set (single object). There are two remote controls (the object reference we created). But it's the same TV set. The Servlet class is a typical single state.
Here's how to create a single-state class:
First the constructor of the class is privatized such as Class test{private Test () {System.out.println ("start Initialization");} Privatization constructor}
The second is that the class contains a member variable that has the same type of member variable as the class itself: the first step is based on the following example: Class a{ private Test () {System.out.println ("start Initialization");} Privatization constructor
Private static Test instance;//defines a member variable of type test,
}
The second is to create a method to return a Test object. This is to consider returning the object with the new test () method. For example, this is: public static test Getnewtest () {return new Test ();} , think of the above we have defined a static variable. If you give it an object. Let's revisit this variable. Because this variable is static, isn't that the same object that was accessed? So you can do this. public static Test getinstance () {
if (Instance==nuul)
Instance =new Test ();
return instance;
}
Because this variable is static, it is the same for the caller. And this static variable points to a single object. When we create this class reference variable, it is essentially a reference to the static variable. The object of natural manipulation is the same.
Paste the code below. It's easier to understand from the code.
class test {public static void main (String[] args) throws Java.lang.exception{tv t1=tv.getinstance (); T1.setname ("TCL"); System.out.println ("Before T2 was created. The brand of the TV is" +t1.getname ()); Tv t2=tv.getinstance (); T2.setname ("Huaxia"); system.out.println ("After the T2 is created, the name of the T1 TV is" + T1.getname ()); system.out.println ("T2 TV's Name" +t2.getname ()); if (t1==t2) System.out.println ("T1 and T2 are the same TV");}} class tv{ private string name; private STATIC TV INSTANCE;    PRIVATE TV () { system.out.println ("Executing constructor ...,"); } public static Tv getinstance () { if (instance==null) instance=new tv (); return instance; } public void SetName (String name) { this.name=name; } public string getname () { return this.name; }}
The code is easy to understand. This also makes one's own study summarizes it.
Java single-State learning