Definition: If a class can always create only one instance, then this class is called a singleton class, and this design pattern is called a singleton pattern.
Within the spring framework, you can set all the generated Bean objects to singleton mode, just specify scope= "singleton" When you configure the Bean instance, or do not configure default as singleton mode.
We can create a small demo to demonstrate the implementation of the singleton pattern, just to make sure that the class can only create one instance, and we can use the permission modifier private to decorate the class's constructor.
Provides an interface for creating this class, which can only be modified with static, creating a member variable inside the class to hold the generated instance.
The code is as follows:
Packagetest;classanmail{}classSinglelondemo {Private StaticSinglelondemo SD; PrivateSinglelondemo () {} Public StaticSinglelondemo single () {if(SD = =NULL) {SD=NewSinglelondemo (); } returnSD; }} Public classsingledemo{ Public Static voidMain (string[] args) {Singlelondemo SD1=Singlelondemo.single (); Singlelondemo SD2=Singlelondemo.single (); System.out.println (SD1==SD2); }}
The output is true to indicate that an instance is being generated.
The singleton pattern is a widely used design pattern, and many frameworks have applications, and the factories in the following factory models require only a single instance.
Two advantages of using singleton mode:
1. Reduce the overhead associated with creating Java instances.
2, easy to track the life cycle of a single Java instance, instance status, and so on.
A single-instance pattern of Java design patterns