`
wangpx
  • 浏览: 198534 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

单例模式 读书笔记

阅读更多
确保一个类只有一个实例,并且只有一个全局访问点。如果使用多个类加载器,可能导致单例模式失效而产生多个实例。单例不允许继承,全局变量也会产生多个实例. 单例模式和工厂模式,抽象工程模式 其实都是为了创建对象,但是单例模式只能产生一个对象实例,而工厂模式可以产生不同类型的对象,抽象工厂模式却能批量产生不同类型的对象。单例模式产生的对象有些孤独,是寡者,没有兄弟,一般对特别重要的资源才可能用到单例模式,这些资源只有一份,就如皇帝,太阳只有一个,皇帝是不希望其他人与他同时也是皇帝的,哪怕是自己的兄弟姐妹。
  • synchronized 对线程同步有作用,但是会降低性能。如果对性能要求不高采用此办法


public class SynchronizedSingleton {
 private  int i=0;
 private static SynchronizedSingleton uninstance=null;
 private void SynchronizedSingleton() {
 }
 public static synchronized SynchronizedSingleton getInstance() {
  if (uninstance == null)
   uninstance= new SynchronizedSingleton();
  
   return uninstance;
 }
 public void hello(){
  System.out.println(++i);
 }
 
}


  • 使用"急切"创建实例,而不用延迟实例化的做法。 此法负担不很繁重。此法依赖JVM加载这个类时马上创建唯一单件实例。JVM保证在任何线程访问uniqueInstance静态变量之前,一定先创建此 实例。


public class EagerlySingleton {
 private  int i=0;
 private static EagerlySingleton uniqueInstance=new EagerlySingleton();
 private EagerlySingleton(){}
 public static EagerlySingleton getInstance(){
  return uniqueInstance;
 }
 public void hello(){
  System.out.println(++i);
 }
}


  • 用“双重检查加锁”,在getInstance中减少使用同步。此方法依赖jdk1.5

public class DoubleCheckedSynchronizedSingleton {
 private  int i = 0;
 private volatile static DoubleCheckedSynchronizedSingleton uninstance = null;
 private void SynchronizedSingleton() {
 }
 public static DoubleCheckedSynchronizedSingleton getInstance() {
  if (uninstance == null) {
   synchronized (DoubleCheckedSynchronizedSingleton.class) {
    if (uninstance == null) {
     uninstance = new DoubleCheckedSynchronizedSingleton();
    }
   }
  }
  return uninstance;
 }
 public void hello() {
  System.out.println(++i);
 }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics