Singleton mode is an object-creation pattern that uses a singleton pattern to guarantee that only one instance object is generated for a class. That is, in the entire program space, there is only one instance object in the class.
that guarantee a class, only one instance exists and provides a globally unique access points that access this class.
Singleton Pattern class Diagram:
In application development, we often have the following requirements:
- between multiple threads, such as servlet environment, share the same resource, or manipulate the same object
- using global variables throughout the program space, sharing resources
- in large-scale systems, for performance reasons, it is necessary to save object creation time and so on.
because Singleton pattern guarantees that only one instance of a class will be generated object, so these cases, Singleton The pattern comes in handy.
the implementation of the Singleton pattern is as follows:
lazy , a hungry man and double
-
check .
Lazy Call Order:
a hungry man call sequence diagram:
The lazy type is the typical time to change the space, the A hungry man type is the typical space change time.
Non-synchronous lazy-type is thread insecure, realize the lazy thread security only add synhronized.
The a hungry man type is thread-safe because the virtual machine guarantees that it will be loaded only once.
"Double check" is to reduce the use of synchronization in getinstance ().
First re-check: Not every time into the Getinstace method to synchronize, but first out of sync, enter the method, first check whether the instance exists, does not exist before entering the following synchronization block.
Second check: Entering the synchronization block will only check again if the instance is present, and it does not exist. Create an instance in the case of synchronization this is the second check.
This will only be synchronized once, thus reducing the number of times of synchronization The time wasted by judging the line .
the essence of the singleton mode is to control the number of instances, when you need to control an instance of a class can have only one, and the customer can only access it from a global access point to choose a singleton mode.
Design pattern Thinking----Single-case mode