一、饿汉

  1. public class Singleton {
  2. private static Singleton instance = new Singleton();
  3. private Singleton() {
  4. }
  5. public static Singleton getInstance() {
  6. return instance;
  7. }
  8. }


二、懒汉

  1. public class LazySingleton {
  2. private static LazySingleton instance;
  3. private LazySingleton() {
  4. }
  5. //每次调用 getInstance() 方法,都需要对这个类加锁
  6. public static synchronized LazySingleton getInstance() {
  7. if (instance == null) {
  8. instance = new LazySingleton();
  9. }
  10. return instance;
  11. }
  12. }

三、双重加锁的懒汉

但是感觉这种写法很丑

  1. public class UglyLazySingleton {
  2. private static UglyLazySingleton instance;
  3. private UglyLazySingleton() {
  4. }
  5. //只有instance=null的时候才需要加锁
  6. public static UglyLazySingleton getInstance() {
  7. if (instance == null) {
  8. synchronized (UglyLazySingleton.class) {
  9. if (instance == null) {
  10. instance = new UglyLazySingleton();
  11. }
  12. }
  13. }
  14. return instance;
  15. }
  16. }

四、使用静态内部类的懒汉

  1. public class LazySingleton {
  2. private LazySingleton() {
  3. }
  4. //静态内部类只有在被使用的时候才会被加载,且只会加载一次
  5. private static class SingletonHolder {
  6. private static LazySingleton instance = new LazySingleton();
  7. }
  8. public static LazySingleton getInstance() {
  9. return SingletonHolder.instance;
  10. }
  11. }