概念

一个类只能创建一个对象,有效减少内存空间占用

实现

  • 私有的构造方法

  • 私有的静态的当前类对象作为属性

  • 公有静态的函数,返回当前类对象

一般写法

  • 饿汉式

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    public class Singleton {
    //构造方法私有
    private Singleton() {}

    private static Singleton instance = new Singleton();

    public static Singleton getInstance() {
    return instance;
    }
    }
  • 懒汉式

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    public class Singleton {
    //构造方法私有
    private Singleton() {}

    private static Singleton instance;

    public static Singleton getInstance() {
    if (null == instance) {
    instance = new Singleton();
    }
    return instance;
    }
    }
  • 线程安全的懒汉式

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    public class Singleton {
    //构造方法私有
    private Singleton() {}

    //加volatile,保证初始化过程中对象唯一
    private static volatile Singleton instance;

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

Next

数据结构(JAVA)