Java的设计模式————单例

单例模式分为:懒汉式(线程不安全),懒汉式(线程安全),饿汉式,双重加锁式,登记式,枚举(不常用)

先介绍简单的4中

 1 1.懒汉式(线程不安全)
 2 public class LazySingleton {
 3         public static  LazySingleton  instance;
 4         private LazySingleton() {}  //主要将构造方法私有化这样在加载该类的时候不会创建对象
 5         public static LazySingleton  getInstance() {
 6             if(instance==null) {
 7                 instance=new LazySingleton();
 8             }
 9             return instance;
10         }
11 }
12 2.懒汉式(线程安全)  //这种方式能够在多线程中很好的工作,
13 public class LazySingleton {
14             
15         public static  LazySingleton  instance;
16         private LazySingleton() {}
17         public static synchronized LazySingleton  getInstance() {  
18             if(instance==null) {
19                 instance=new LazySingleton();
20             }
21             return instance;
22         }
23 }
24 3.饿汉式
25 public class hungrySingleton {
26         private static  hungrySingleton  instance = new hungrySingleton();
27         
28         private hungrySingleton() {}
29         
30         public static  hungrySingleton getInstance() {
31             return instance;
32         }
33     
34 }
35 4.双重加索
36 /**
37  * volatie 保持原子性
38  * ,因此也就不会使执行线程阻塞,
39  * 因此volatile变量是防止多线程运行
40  * sychronize时候instance初始化时候引用错误
41  * 
42  *
43  */
44 public class lockSingleton {
45             private static volatile lockSingleton  instance;  
46             private  lockSingleton() {}
47             
48             public static lockSingleton  getInstance () {
49                 synchronized(lockSingleton.class) {
50                     if(instance==null) {
51                         instance=new lockSingleton();
52                     }
53                     return instance;
54                 }
55                 
56             }
57             
58 }
posted @ 2019-12-17 10:36  自律的人真可怕  阅读(170)  评论(0)    收藏  举报