饿汉式

    1. /*静态常量饿汉式*/
    2. public class HungryStaticCode {
    3. private final static HungryStaticCode hungryStaticCode = new HungryStaticCode();
    4. private HungryStaticCode() {}
    5. public static HungryStaticCode getInstance() {
    6. return hungryStaticCode;
    7. }
    8. }
    9. /*静态块饿汉式*/
    10. public class SingletonBlock {
    11. private static SingletonBlock singletonBlock;
    12. static {
    13. singletonBlock = new SingletonBlock();
    14. }
    15. public static SingletonBlock getInstance() {
    16. return singletonBlock;
    17. }
    18. }
    19. //类装载时就完成了实例化,可能会造成内存浪费

    懒汉式

    1. /*线程不安全懒汉式*/
    2. public class LazyNoSafe {
    3. private static LazyNoSafe lazyNoSafe;
    4. private LazyNoSafe() {}
    5. public static LazyNoSafe getInstance() {
    6. if (lazyNoSafe == null) {
    7. lazyNoSafe = new LazyNoSafe();
    8. }
    9. return lazyNoSafe;
    10. }
    11. }
    12. /*线程安全懒汉式*/
    13. public class LazySafe {
    14. private static LazySafe lazyNoSafe;
    15. private LazySafe() {}
    16. public static synchronized LazySafe getInstance() {
    17. if (lazyNoSafe == null) {
    18. lazyNoSafe = new LazySafe();
    19. }
    20. return lazyNoSafe;
    21. }
    22. }
    23. /*同步代码块懒汉式-----不可使用*/
    24. public class LazyBlock {
    25. private static LazyBlock lazyBlock;
    26. private LazyBlock() {}
    27. public static LazyBlock getInstance() {
    28. if (lazyBlock == null) {
    29. synchronized (LazyBlock.class) {
    30. lazyBlock = new LazyBlock();
    31. }
    32. }
    33. return lazyBlock;
    34. }
    35. }

    双重检测模式

    1. public class DoubleSafe {
    2. private static DoubleSafe doubleSafe;
    3. private DoubleSafe () {}
    4. public static DoubleSafe getInstance() {
    5. if (doubleSafe == null) {
    6. synchronized (DoubleSafe.class) {
    7. if (doubleSafe == null) {
    8. doubleSafe = new DoubleSafe();
    9. }
    10. }
    11. }
    12. return doubleSafe;
    13. }
    14. }

    静态内部类延迟加载(推荐使用)
    懒加载+类第一次加载才会初始化,在初始化的时候别的线程无法进入,保证了线程安全

    1. public class StaticInside {
    2. private static volatile StaticInside staticInside;
    3. private StaticInside() {}
    4. private static class StaticInsideInstance {
    5. private static final StaticInside STATIC = new StaticInside();
    6. }
    7. public static synchronized StaticInside getInstance() {
    8. return StaticInsideInstance.STATIC;
    9. }
    10. }