Children's shoes, who have known about spring frames, know what the spring Bean's default form is? ——— single-Case form.
Q: What is called a singleton? The singleton is actually Singleton, as the name implies is only a single instance object operation.
So why use a single case?
As for this question, let's take a look at the code before we explain it:
Package Me.javen.oop;public class Singletondemo {public static void main (string[] args) {Singleton singleton1 = Singleton. GetInstance (); Singleton Singleton2 = Singleton.getinstance (); System.out.println (Singleton1 = = Singleton2);}} Class Singleton{private static Singleton singleton;public static Singleton getinstance () {//Provide unique object acquisition port if (Singleton = = NULL) {singleton = new Singleton ();} return singleton;} Private Singleton () {//Privatized construction method System.out.println ("Create once ~");}}
I want to ask comrades, what is the output of this?
Run the output result:
Create only once ~
True
We can see that singleton1 and singleton2 are equal, meaning that the two objects are the same object.
First, let's look at how privatization is structured:
This means that you cannot create an object with the New keyword when you use the Singleton class externally. The following will be an error:
is not new, then how do we use the Singleton class?
Disclosed in the following ways:
public static Singleton getinstance () {//provides a unique object get port if (Singleton = = null) {Singleton = new Singleton ();} return singleton;}
Can we not provide such a method?
Of course, just do not provide such a way, you this class really can not make the ~
Now to answer the opening question, why use a singleton?
1, reduce unnecessary memory overhead, you want to ah, if you create 10 objects, you have to spend 10 minutes of memory, and a singleton 1 objects, of course, cost 1 parts of memory.
If we could reduce the memory overhead, could we design the class as a singleton? This is not very memory-saving. This question, first do not explain ha ~ left to learn good children's shoes thinking
2. Simplify the complexity of the object creation process. How to say this, to see the complexity of object creation ~