Skip to content

Commit c97cdca

Browse files
authored
单例模式
单例模式
1 parent 8f3c71c commit c97cdca

File tree

4 files changed

+93
-0
lines changed

4 files changed

+93
-0
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package com.java.design.singleton;
2+
3+
/**
4+
* 单例模式的实现:饿汉式,线程安全 但效率比较低
5+
*/
6+
public class SingletonA {
7+
8+
private SingletonA() {
9+
}
10+
11+
private static final SingletonA instance = new SingletonA();
12+
13+
public static SingletonA getInstance() {
14+
15+
return instance;
16+
}
17+
18+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package com.java.design.singleton;
2+
3+
/**
4+
* 单例模式的实现:饱汉式,非线程安全
5+
*/
6+
public class SingletonB {
7+
8+
// 防止实例化
9+
private SingletonB() {
10+
11+
}
12+
13+
// 定义一个SingletonTest类型的变量(不初始化,注意这里没有使用final关键字)
14+
private static SingletonB instance;
15+
16+
// 定义一个静态的方法(调用时再初始化SingletonTest,但是多线程访问时,可能造成重复初始化问题)
17+
// 加上 synchronized 保证线程安全
18+
public static synchronized SingletonB getInstance() {
19+
20+
if (instance == null) {
21+
instance = new SingletonB();
22+
}
23+
return instance;
24+
}
25+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package com.java.design.singleton;
2+
3+
/**
4+
* 单例模式最优方案 线程安全 并且效率高
5+
*/
6+
public class SingletonC {
7+
8+
private SingletonC() {
9+
10+
}
11+
12+
// 定义一个静态私有变量(不初始化,不使用final关键字,使用volatile保证了多线程访问时instance变量的可见性,避免了instance初始化时其他变量属性还没赋值完时,被另外线程调用)
13+
private static volatile SingletonC instance;
14+
15+
public static SingletonC getInstance() {
16+
if (instance == null) {
17+
// 同步代码块(对象未初始化时,使用同步代码块,保证多线程访问时对象在第一次创建后,不再重复被创建)
18+
synchronized (SingletonC.class) {
19+
if (instance == null) {
20+
instance = new SingletonC();
21+
}
22+
}
23+
}
24+
return instance;
25+
}
26+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package com.java.design.singleton;
2+
3+
/**
4+
* 静态内部类
5+
*
6+
* @author Administrator
7+
*
8+
*/
9+
public class SingletonD {
10+
11+
private static class SingletonHolder {
12+
13+
private static final SingletonD INSTANCE = new SingletonD();
14+
}
15+
16+
private SingletonD() {
17+
18+
}
19+
20+
public static SingletonD getInstance() {
21+
22+
return SingletonHolder.INSTANCE;
23+
}
24+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy