File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package a03_Singleton ;
2+
3+ /**
4+ * 单例模式 - 懒汉式 (性能 换 资源)
5+ *
6+ */
7+ public class Singleton2 {
8+
9+ /* 持有私有静态实例,防止被引用,此处赋值为null,目的是实现延迟加载 */
10+ private static Singleton2 instance = null ;
11+
12+ /* 私有构造方法,防止被实例化 */
13+ private Singleton2 () {
14+ }
15+
16+ /* 静态工程方法,创建实例 */
17+ public synchronized static Singleton2 getInstance () {
18+ if (instance == null ) {
19+ instance = new Singleton2 ();
20+ }
21+ return instance ;
22+ }
23+
24+ }
Original file line number Diff line number Diff line change 1+ package a03_Singleton ;
2+
3+ /**
4+ * 单例模式 - 双重检查
5+ *
6+ */
7+ public class Singleton3 {
8+
9+ /* 持有私有静态实例,防止被引用,此处赋值为null,目的是实现延迟加载 */
10+ private static volatile Singleton3 instance = null ;
11+
12+ /* 私有构造方法,防止被实例化 */
13+ private Singleton3 () {
14+ }
15+
16+ /* 静态工程方法,创建实例 */
17+ public static Singleton3 getInstance () {
18+ //double check
19+ if (instance == null ) {
20+ synchronized (instance ) {
21+ if (instance == null ) {
22+ instance = new Singleton3 ();
23+ }
24+ }
25+ }
26+ return instance ;
27+ }
28+
29+ }
You can’t perform that action at this time.
0 commit comments