码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式-单例模式

时间:2017-01-20 00:16:58      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:block   logs   zed   instance   bsp   blog   static   one   on()   

第一种方式:通过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

 

设计模式-单例模式

标签:block   logs   zed   instance   bsp   blog   static   one   on()   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!