Problem Description: Design the implementation of a singleton pattern.
Analysis: A singleton pattern, which requires that a class have and have only one instance object throughout the program. Because at some point, we just need to have an object in the class, so we can implement this class in a singleton pattern,
For example, some objects of the system, such as time, can be designed as singleton patterns.
There are two types of common singleton patterns: a hungry man mode and lazy mode. The specific differences are as follows:
A hungry man mode: Slow when loading classes (because you want to create objects), run-time gets objects faster, thread-safe
Lazy mode: Faster when loading classes (because no objects are created), slow to get objects at run time, thread insecure
To make it easier for the reader to understand, I wrote the following Java code, which implements the A hungry man mode and the lazy mode, which the reader can understand in conjunction with the code:
The A Hungry man mode is as follows:
1 /*2 * Implementation of a hungry man mode Singleton13 */4 Public classSingleton1 {5 //1. Privatize the construction method and do not allow external direct creation of objects6 PrivateSingleton1 () {7 8 }9 //2. Create a unique instance of a classTen Private StaticSingleton1 instance=NewSingleton1 (); One //3. Provide a method for obtaining an instance A Public StaticSingleton1 getinstance () { - returninstance; - } the -}
The lazy mode is as follows:
1 /*2 * The realization of lazy mode Singleton23 */4 Public classSingleton2 {5 //1. Privatize the construction method and do not allow external direct creation of objects6 PrivateSingleton2 () {7 8 }9 //2. Create a unique instance of a classTen Private StaticSingleton2 instance; One //3. Provide a method for obtaining an instance A Public StaticSingleton2 getinstance () { - if(instance==NULL) -Instance=NewSingleton2 (); the returninstance; - } -}
The test code is as follows:
1 Public classTest {2 3 Public Static voidMain (string[] args) {4 //TODO Auto-generated method stubs5Singleton1 s1=singleton1.getinstance ();6Singleton1 s2=singleton1.getinstance ();7 if(s1==S2) {8System.out.println ("S1 and S2 are the same instance");9 }Ten ElseSystem.out.println ("S1 and S2 are not the same instance"); One ASingleton2 s3=singleton2.getinstance (); -Singleton2 s4=singleton2.getinstance (); - if(s3==S4) { theSystem.out.println ("S3 and S4 are the same instance"); - } - ElseSystem.out.println ("S3 and S4 are not the same instance"); - } + -}
The output is:
S1 and S2 are the same instance
S3 and S4 are the same instance
Single-Case mode