首页 > 其他 > 详细

设计模式-单例模式

时间:2017-01-20 00:15:13      阅读:276      评论:0      收藏:0      [点我收藏+]

第一种方式:通过synchronized解决,性能下降

技术分享
 1 package singleton;
 2 
 3 public class Singleton {
 4     private Singleton() {
 5     }
 6 
 7     private static Singleton instance ;
 8 
 9     public static synchronized Singleton getInstance() {
10         if (instance == null) { 
11             synchronized (instance) {
12                 instance = new Singleton(); 
13             }
14         }
15         return instance;
16     }
17 }
View Code

第二种方式:JVM加载这个类时马上创建唯一的单件,可能创建时负担太重而该单件未使用,造成浪费.

技术分享
 1 package singleton;
 2 
 3 public class Singleton {
 4     private Singleton() {
 5     }
 6 
 7     private static Singleton instance = new Singleton();
 8 
 9     public static Singleton getInstance() {
10         return instance;
11     }
12 }
View Code

第三种方式:双重检查加锁

技术分享
 1 package singleton;
 2 
 3 public class Singleton {
 4     private Singleton() {
 5     }
 6 
 7     /**
 8      * volatile确保当instance被初始化成Singleton实例时,多个线程正确的处理instance变量
 9      */
10     private volatile static Singleton instance;
11 
12     public static Singleton getInstance() {
13         if (instance != null) {
14             synchronized (Singleton.class) {
15                 if (instance != null) {
16                     instance = new Singleton();
17                 }
18             }
19         }
20         return instance;
21     }
22 }
View Code

 

设计模式-单例模式

原文:http://www.cnblogs.com/crazyhusky/p/6309074.html

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