Because design patterns are very important for Java advanced developers, there are many articles about design patterns, blogs, etc. on the web. So, first I do a simple summary of the relatively simple singleton pattern.
First, the way of realization
There are 3 ways to implement the singleton mode, namely, a hungry man type, lazy type, Iodh 3 kinds, the following respectively introduces each kind of realization principle and merits and demerits.
A) A hungry man type
Implementation principle: A class has a static member variable, and the initialized value is an instantiated object itself.
Pros: Even multi-threaded concurrent access ensures that only one object is available, and can be quickly responded to when the object is fetched.
Disadvantage: When classes are loaded, objects are created, resulting in low resource utilization.
b) Lazy type
Implementation principle: Create object in static method, member variable is modified by volatile, method is implemented by double check lock.
Pros: Lazy loading improves memory resource utilization.
Disadvantage: Because the volatile keyword will block the Java Virtual machine to do some code optimization, so the system operation efficiency is reduced.
c) Iodh (initialization Demand Holder)
Implementation principle: Add a static inner class, create a singleton object in the inner class, and return the singleton object to external use through the getinstance () method, which is guaranteed to be thread-safe by the Java Virtual machine.
Pros: Lazy loading can ensure thread safety without compromising system performance.
Disadvantage: Many object-oriented languages do not support Iodh, which is related to the characteristics of the language itself (because it is guaranteed to be thread-safe by a Java Virtual machine).
Second, single case mode application scenario
Database connection pooling, thread pooling, log processing, counters, sevice, and DAO are usually also singleton.
Java single-instance mode experience