File tree Expand file tree Collapse file tree
src/designpattern/singleton Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package designpattern .singleton ;
2+
3+ /**
4+ * 单例类,使用饿汉式,线程安全(不存在同步问题,但是类被加载即被初始化,特定条件下耗费内存);注释为饱汉式,存在线程不安全的问题
5+ *
6+ * @author liu yuning
7+ *
8+ */
9+ public class Singleton {
10+
11+ // 饱汉式
12+ // private static Singleton instance;
13+
14+ // 饿汉式
15+ private static final Singleton instance = new Singleton ();
16+
17+ private Singleton () {
18+
19+ }
20+
21+ public static Singleton getInstance () {
22+ // 饱汉式
23+ // if (instance == null) {
24+ // instance = new Singleton();
25+ // }
26+
27+ return instance ;
28+ }
29+
30+ }
Original file line number Diff line number Diff line change 1+ package designpattern .singleton ;
2+
3+ /**
4+ * 单例模式客户端
5+ *
6+ * @author liu yuning
7+ *
8+ */
9+ public class SingletonClient {
10+ public static void main (String [] args ) {
11+
12+ SingletonThreadSafe instance1 = SingletonThreadSafe .getInstance ();
13+ SingletonThreadSafe instance2 = SingletonThreadSafe .getInstance ();
14+
15+ if (instance1 .equals (instance2 )) {
16+ System .out .println ("同样的实例" );
17+ } else {
18+ System .out .println ("不同的实例" );
19+ }
20+
21+ }
22+
23+ }
Original file line number Diff line number Diff line change 1+ package designpattern .singleton ;
2+
3+ /**
4+ * 线程安全的写法,单例模式最优写法
5+ *
6+ * @author liu yuning
7+ *
8+ */
9+ public class SingletonThreadSafe {
10+ private static volatile SingletonThreadSafe instance ;
11+
12+ private SingletonThreadSafe () {
13+
14+ }
15+
16+ public static SingletonThreadSafe getInstance () {
17+ if (instance == null ) {
18+ synchronized (SingletonThreadSafe .class ) {
19+ if (instance == null ) {
20+ instance = new SingletonThreadSafe ();
21+ }
22+ }
23+ }
24+
25+ return instance ;
26+ }
27+
28+ }
You can’t perform that action at this time.
0 commit comments