导航
导航
Posts List
  1. Java单例模式总结
  2. 基本模式
    1. 分类
      1. 单线程条件下:根据初始化的时间不同
      2. 多线程条件下:通过不同的方式来保证饿汉式的线程安全

Java单例模式总结

Java单例模式总结


基本模式

  1. 将构造方法设为私有,使得在外部无法通过new来创建对象,将实例对象的生成控制权由类内部自己控制。
  2. 因为通过new来实例化对象,所以只有通过类的静态对象来获取单例对象。
  3. 因为获取实力对象是静态的,所以类中的单例对象成员也必须要是静态。

分类

单线程条件下:根据初始化的时间不同
  • 懒汉式

    code:

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

    适用条件:

    1. 在单线程的条件下
    2. 适用在单例对象初始化非常快,并且内存占用比较小的时候。
  • 饿汉式

    code:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    public class Singleton{
    private static Singleton singleton = null;
    private Singleton(){}
    public static Singleton getInstance(){
    if(singleton == null){
    singleton = new Singleton();
    return singleton;
    }
    }
    }

    适用条件:

    1. 单例提供的功能非常复杂,而且需要消耗大量资源来初始化单例
多线程条件下:通过不同的方式来保证饿汉式的线程安全
  • 同步锁/双重校验锁

    同步锁:

    code:

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

    双重同步锁:
    code:如果已经有了单例对象,则不去加载同步锁,减少消耗,提高性能

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    public class Singleton{
    private static Singleton singleton = null;
    private Singleton(){}
    public static Singleton getInstance(){
    if(singleton == null){
    synchronized(Singleton.class){
    if(singleton == null){
    singleton = new Singleton();
    }
    }
    }
    return singleton;
    }
    }
  • 静态内部类:通过JVM进行类加载的时候会保证数据是同步的来实现单例模式

    code:

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

    code:

    1
    2
    3
    public enum Singleton{
    instance;
    }