首页 > 其他 > 详细

单例模式--singleton

时间:2020-03-03 12:27:15      阅读:58      评论:0      收藏:0      [点我收藏+]

单例模式就是说无论程序如何运行,采用单例设计模式永远只会有一个实例化对象产生

(1)将采用单例设计模式的构造方法私有化。
(2)在其内部产生该类的实例化对象,并将其封装成private static类型。
(3)定义一个静态方法返回该类的示例。

 1 /**  
 2  *   
 3  * 单例模式的实现:饿汉式,线程安全 但效率比较低  
 4  */  
 5 public class SingletonTest {   
 6   
 7     private SingletonTest() {   
 8     }   
 9   
10     private static final SingletonTest instance = new SingletonTest();   
11   
12     public static SingletonTest getInstancei() {   
13         return instance;   
14     }   
15   
16 }  
17 
18 
19 /**  
20  * 单例模式的实现:饱汉式,非线程安全   
21  *   
22  */  
23 public class SingletonTest {   
24     private SingletonTest() {   
25     }   
26   
27     private static SingletonTest instance;   
28   
29     public static SingletonTest getInstance() {   
30         if (instance == null)   
31             instance = new SingletonTest();   
32         return instance;   
33     }   
34 }  
35 
36 
37 /**  
38  * 线程安全,但是效率非常低  
39  * @author vanceinfo  
40  *  
41  */  
42 public class SingletonTest {   
43     private SingletonTest() {   
44     }   
45   
46     private static SingletonTest instance;   
47   
48     public static synchronized SingletonTest getInstance() {   
49         if (instance == null)   
50             instance = new SingletonTest();   
51         return instance;   
52     }   
53 }  
54 
55 /**  
56  * 线程安全  并且效率高  
57  *  
58  */  
59 public class SingletonTest {   
60     private static SingletonTest instance;   
61   
62     private SingletonTest() {   
63     }   
64   
65     public static SingletonTest getIstance() {   
66         if (instance == null) {   
67             synchronized (SingletonTest.class) {   
69                instance = new SingletonTest();   71             }   
72         }   
73         return instance;   
74     }   
75 }  

 

单例模式--singleton

原文:https://www.cnblogs.com/ivy-xu/p/12401306.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!