单实例模式学习笔记


1. 经典的单实例模式例子(非线程安全):
public class Singleton {
    private static Singleton uniqueInstance;
 
    // other useful instance variables here
 
    private Singleton() {}
 
    public static Singleton getInstance() {
        if (uniqueInstance == null) {
        uniqueInstance = new Singleton();
     }
         return uniqueInstance;
    }
 
    // other useful methods here
}
本例是最经典的单实例模式例子,但是在多线程的情况下就会产生多个实例!

2. 线程安全的例子:
public class Singleton {
 private static Singleton uniqueInstance;
 
 // other useful instance variables here
 
 private Singleton() {}
 
 public static synchronized Singleton getInstance() {
  if (uniqueInstance == null) {
   uniqueInstance = new Singleton();
  }
  return uniqueInstance;
 }
 
 // other useful methods here
}
增加synchronized,会让该方法是线程安全的,但是会引起每个线程在调用该方法时的等待,如果getInstance的性能对应用程序不是很关键(记住,同步方法可能会使getInstance方法得运行效率降低100倍),本方法是最好得方法!
3. 提前实例化,不适用延迟实例化(使用于创建和运行时负担不太繁重或者应用程序总是创建并使用单件实例),它是线程安全得:
public class Singleton {
    private static Singleton uniqueInstance = new Singleton();

    // other useful instance variables here
 
    private Singleton() {}
 
    public static Singleton getInstance() {
            return uniqueInstance;
    }
 
    // other useful methods here
}
采用这种方法,我们依赖JVM在加载这个类时候马上创建此唯一实例,JVM保证在任何线程访问它之前,一定先创建它!
4. 在java1.5及以后的版本,增加了volatile关键字,可以采用双重检查加锁!
public class Singleton {
 private volatile static Singleton uniqueInstance;
 
 private Singleton() {}
 
 public static Singleton getInstance() {
  if (uniqueInstance == null) {
   synchronized (Singleton.class) {
    if (uniqueInstance == null) {
     uniqueInstance = new Singleton();
    }
   }
  }
  return uniqueInstance;
 }
}
volatile关键字确保:当unigueInstance变量在被初始化成实例时,多个线程能够正确的处理它!(对于关注性能的程序,这种做法可以大大减少时耗)



posted on 2008-05-04 08:38 扭转乾坤 阅读(652) 评论(0)  编辑  收藏 所属分类: 设计模式


只有注册用户登录后才能发表评论。


网站导航:
 
<2008年5月>
27282930123
45678910
11121314151617
18192021222324
25262728293031
1234567

导航

统计

常用链接

留言簿(2)

随笔分类(31)

随笔档案(30)

文章分类(32)

文章档案(33)

相册

PHP小站-首页

搜索

积分与排名

最新评论

阅读排行榜

评论排行榜