饿汉式单例和懒汉式单例
单例模式:
1.单例类只能创建一个实例;
2.单例类必须自己创建自己的唯一实例;
3.单例类必须给其他所有对象提供这一实例。
饿汉式单例: 线程安全
public class Singleton {
//饿汉式单例 线程安全
//无论是饿汉式还是懒汉式 都要私有构造方法!
//1.私有构造方法
private Singleton() {
}
//2.定义一个当前类型的静态变量,并私有化.(创建一个唯一实例)
private static Singleton instance = new Singleton();
//3.定义一个静态的方法,用来返回当前的唯一实例
public static Singleton getInstance() {
return instance;
}
}
懒汉式单例:非线程安全
//懒汉式单例 非线程安全
//所谓懒 就是用的时候再创建 不用不创建
//1.私有构造方法
private Singleton() {
}
//2.定义一个当前类型的静态变量,并私有化.(创建一个唯一实例)
//volatile是为了保证线程的可见性
private static volatile Singleton instance; // 或写成Singleton instance==null; instance默认是null
//3.定义一个静态的方法,用来返回当前的唯一实例
public static Singleton getUser() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
如果想让懒汉式单例成为线程安全的,在第3步加一个synchronized (类名.class)
public static Singleton getInstance() {
if (instance == null) {
//之所以在外层加个if,是因为让加锁的时机延后,这样可以提高效率
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}