Head first design mode note (6) --- single-piece Mode
Single-piece mode: the single-piece mode ensures that a class has only one instance and provides a global access point.
The single-piece mode only involves one class, so it is very simple. Note the following two points: (1) the constructor is a private member; (2) there is a static function that is responsible for instantiation.
Question 1: the dilemma of single-piece mode in multi-thread mode
Answer 1: There are three methods to process the single-piece mode in multiple threads:
(1) synchronization mechanism:
The synchronization method is simple and effective, but it may cause inefficiency. Synchronizing a method may reduce the execution efficiency by 100 times, so it is not suitable for frequent operations.
(2) Use "eager" to create an instance without delay. For details, see:
(3) "double check lock", reduce the use of synchronization in getinstance (), see:
Note: Volatile keyword reference: http://aleung.blogbus.com/logs/32090434.html