Sometimes in the actual project development, we encounter a situation where the class only allows an instantiated object, does not allow more than one instantiation object, we refer to this situation as a singleton pattern in the Java design pattern. The design of the singleton mode mainly uses the Java private and static keyword attributes. The singleton mode is divided into Lazy singleton mode and a hungry man type singleton mode according to whether the delay loading instance process.
For example, here is an understanding of a requirement that conforms to the singleton pattern. Suppose the person is divided into ordinary people and Superman, the majority of the earth is normal, and Superman only one, we should be in the creation of these two entity classes should use a singleton mode. The following is the code implementation of the lazy and the Han-style singleton patterns, respectively:
The realization of the lazy single-case mode:
1 classsuperman3{//Lazy Type2 PrivateSuperMan3 () {//Privatization Constructor3 4 }5 Public StaticSuperMan3 s3 =NULL;6 Public StaticSuperMan3 getinstance () {7 if(s3==NULL){8S3 =NewSuperMan3 ();9 }Ten returnS3; One } A}
The code implementation of the A Hungry man-mode singleton pattern:
1 classsuperman4{//Bad Han style2 PrivateSuperMan4 () {//Privatization Constructor3 4 }5 Private StaticSuperMan4 S4 =NewSuperMan4 ();6 Public StaticSuperMan4 getinstance () {7 returnS4;8 }9}
It can be seen that the name of the lazy and a hungry man-style or very vivid, the specific lazy and a hungry man-type single-case mode of online security and resource occupancy There are many differences, here is not detailed description. Then verify that the two hyper-humans satisfy the singleton pattern, we can create two instances in the main function, and then compare whether they are equal.
1 SuperMan3 s3 = superman3.getinstance (); 2 SuperMan3 S33 = superman3.getinstance (); 3 System.out.println (S3==S33); // true 4 5 SuperMan4 S4 = superman4.getinstance (); 6 SuperMan4 s44 = superman4.getinstance (); 7 System.out.println (S4==S44); // true
The output is true, and you can see that no matter how many instances are instantiated, the final instances are all equal, that is, there is only one instance that satisfies the requirements of the singleton pattern.
Singleton patterns in Java design mode