Design Patterns-singleton patterns
The Singleton mode is an object creation mode. The Singleton mode ensures that only unique instance objects are generated for a class. That is to say, in the whole program space, the class only has one instance object.
This ensures that only one instance exists for a class and provides a globally unique access point for this class.
Singleton mode class diagram:
In application system development, we often have the following requirements:
-Multiple Threads, such as the servlet environment, share the same resource or operate on the same object
-Use global variables in the entire program space to share resources
-In a large-scale system, you need to save the object creation time for performance considerations.
Because the Singleton mode can ensure that only unique instance objects are generated for a class, the Singleton mode will be used in these cases.
The Singleton mode is implemented as follows:
Lazy,
Hungry Chinese StyleAnd
Double check.
LazyCall sequence:
Hungry Chinese StyleCall Sequence diagram:
Lazy is a typical time-to-space change, while hungry is a typical space-to-time change.
The lazy mode without synchronization is thread unsafe. To implement the lazy thread security, you only need to add synhronized.
The hunger style is thread-safe, because the Virtual Machine ensures that it will only load once.
"Double Check"That is, reduce the use of synchronization in getInstance.
The first check: Do not synchronize the getInstace method every time you enter the getInstace method. Instead, do not synchronize the getInstace method. After Entering the method, check whether the instance exists and does not exist before entering the following synchronization block.
The second check: Entering the synchronization block will only check whether the instance exists again. If the instance does not exist, it will create an instance in the case of synchronization. This is the second check.
In this way, only one synchronization is required, which reduces the time wasted on judgment when multiple synchronization operations are performed.
The Singleton mode is essentially to control the number of instances. When you need to control only one instance of a class, and the customer can only access it from one global access point, you can select the singleton mode.