首页 > 其他 > 详细

单例模式

时间:2015-08-29 20:21:28      阅读:210      评论:0      收藏:0      [点我收藏+]

1、饿汉式:

/**
 * 缺点:没有达到lazy loading的效果
 */ 
public class Singleton {
 private static Singleton instance = new Singleton();
 private Singleton() {
 }
 public static Singleton getInstance() {
  return instance;
 }
}

2、懒汉式:

class Singleton {
 private static Singleton instance = null;
 private Singleton() {
 }
 public static synchronized Singleton getInstance() {
  if (instance == null)
   instance = new Singleton();
  return instance;
 }
}

3、双重校验锁:

/**
 *双重校验锁,在当前的内存模型中无效
 */ 
class Singleton {
 private static Singleton instance = null;
 private Singleton() {
 }
 public static synchronized Singleton getInstance() {
  if (instance == null)
   synchronized (Singleton.class) {
    if (instance == null)
     instance = new Singleton();
   }
  return instance;
 }
}

4、静态内部类:

/**
 * 优点:加载时不会初始化静态变量instance ,因为没有主动使用,达到Lazy loading
 */ 
class Singleton {
 private static class SingletonHolder {
  private final static Singleton instance = new Singleton();
 }
 private Singleton() {
 }
 public static Singleton getInstance() {
  return SingletonHolder.instance;
 }
}

5、枚举:

/**
 * Effective Java》作者推荐使用的方法,优点:不仅能避免多线程同步问题,而且还能防止反序列化重新创建新的对象
 */ 
enum EnumSingleton{
    instance;
    public void doSomeThing(){
    }
}

单例模式

原文:http://my.oschina.net/u/2350638/blog/499040

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