单例模式八种写法

2018-10-14  本文已影响0人  Yue_Q
  • 1. 饿汉式(静态常量)[可用]
public class Singleton {

   private final static Singleton INSTANCE = new Singleton();

   private Singleton(){}

   public static Singleton getInstance(){
       return INSTANCE;
   }
}

优点:这种写法比较简单,就是在类装载的时候就完成实例化。避免了线程同步问题。
缺点:在类装载的时候就完成实例化,没有达到Lazy Loading的效果。如果从始至终从未使用>过这个实例,则会造成内存的浪费

  • 2. 饿汉式(静态常量)[可用]
public class Singleton {

   private static Singleton instance;

   static {
       instance = new Singleton();
   }

   private Singleton() {}

   public Singleton getInstance() {
       return instance;
   }
}

采用静态代码块架子与以上优点缺点一样。

  • 3. 懒汉式(线程不安全)[不可用]
public class Singleton {

  private static Singleton singleton;

   private Singleton() {}

   public static Singleton getInstance() {
       if (singleton == null) {
           singleton = new Singleton();
       }
       return singleton;
   }
}

这种写法起到了Lazy Loading的效果,但是只能在单线程下使用。如果在多线程下,一个线程进入了if (singleton == null)判断语句块,还未来得及往下执行,另一个线程也通过了这个判断语句,这时便会产生多个实例。所以在多线程环境下不可使用这种方式。

  • 4. 懒汉式(线程安全,同步方法)[不推荐用]
public class Singleton {

   private static Singleton singleton;

   private Singleton() {}

   public static synchronized Singleton getInstance() {
       if (singleton == null) {
           singleton = new Singleton();
       }
       return singleton;
  }
}

效率太低了,每个线程在想获得类的实例时候,执行getInstance()方法都要进行同步

  • 5、双重检查[推荐用]
public class Singleton {

  private static volatile Singleton singleton;

  private Singleton() {}

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

我们进行了两次if (singleton == null)检查,这样就可以保证线程安全了。这样,实例化代码只用执行一次,后面再次访问时,判断if (singleton == null),直接return实例化对象

  • 6、静态内部类[推荐用]
public class Singleton {

   private Singleton() {}

   private static class SingletonInstance {
       private static final Singleton INSTANCE = new Singleton();
   }

   public static Singleton getInstance() {
       return SingletonInstance.INSTANCE;
   }
}

优点:利用类中静态变量唯一性JVM 本身的机制保证数据线程安全,没有使用 synchronized 效率高,SingletonInstance 是 private 的外部类无法访问。

  • 7、枚举[推荐用]
public enum Singleton {
   INSTANCE;
   public void whateverMethod() {

   }
}

借助JDK1.5中添加的枚举来实现单例模式。不仅能避免多线程同步问题,而且还能防止反序列化重新创建新的对象。可能是因为枚举在JDK1.5中才添加,所以在实际项目开发中,很少见人这么写过。
优点:系统内存中该类只存在一个对象,节省了系统资源,对于一些需要频繁创建销毁的对象,使用单例模式可以提高系统性能。
缺点:当想实例化一个单例类的时候,必须要记住使用相应的获取对象的方法,而不是使用new,可能会给其他开发人员造成困扰,特别是看不到源码的时候。

适用场合:

  1. 需要频繁的进行创建和销毁的对象;
  2. 创建对象时耗时过多或耗费资源过多,但又经常用到的对象;
  3. 工具类对象;
  4. 频繁访问数据库或文件的对象。

Android 中的单例

Android 中的 Application 是单例模式的,系统启动时候会创建,它的生命周期等同于 Activity 整个生命周期。Application 是 Android 中唯一的实例。
在Android中,可以通过继承Application类来实现应用程序级的全局变量,这种全局变量方法相对静态类更有保障,直到应用的所有Activity全部被destory掉之后才会被释放掉。

上一篇下一篇

猜你喜欢

热点阅读