单例模式:
一个类只允许创建一个实例对象,并提供访问其唯一的对象的方式。这个类就是一个单例类,这种设计模式叫作单例模式。
作用:
避免频繁创建和销毁系统全局使用的对象。
单例模式的特点:
应用场景:
饿汉式与懒汉式的区别:
线程安全性问题:
饿汉式,在被调用 getInstance() 方法时,单例已经由 jvm 加载初始化完成,所以并发访问 getInstance() 方法返回的都是同一实例对象,线程安全。
懒汉式,要保证线程安全,可以有以下几种方式:
示例代码:
1、饿汉式
package constxiong.interview;
/**
* 单例模式 饿汉式
* @author ConstXiong
*/
public class TestSingleton {
private static final TestSingleton instance = new TestSingleton();
private TestSingleton() {
}
public static TestSingleton getInstance() {
return instance;
}
}
2、懒汉式:线程不安全
package constxiong.interview;
/**
* 单例模式 懒汉式-线程不安全
* @author ConstXiong
*/
public class TestSingleton {
private static TestSingleton instance;
private TestSingleton() {
}
public static TestSingleton getInstance() {
if (instance == null) {
instance = new TestSingleton();
}
return instance;
}
}
3、懒汉式:getInstance() 方法加锁,线程安全,性能差
package constxiong.interview;
/**
* 单例模式 懒汉式-加锁
* @author ConstXiong
*/
public class TestSingleton {
private static volatile TestSingleton instance;
private TestSingleton() {
}
public static synchronized TestSingleton getInstance() {
if (instance == null) {
instance = new TestSingleton();
}
return instance;
}
}
4、懒汉式:双重检查 + 对类加锁
package constxiong.interview;
/**
* 单例模式 懒汉式-双重检查 + 对类加锁
* @author ConstXiong
*/
public class TestSingleton {
private static volatile TestSingleton instance;
private TestSingleton() {
}
public static TestSingleton getInstance() {
if (instance == null) {
synchronized (TestSingleton.class) {
if (instance == null) {
instance = new TestSingleton();
}
}
}
return instance;
}
}
5、懒汉式:静态内部类
package constxiong.interview;
/**
* 单例模式 懒汉式-静态内部类
* @author ConstXiong
*/
public class TestSingleton {
private static class SingletonHolder {
private static final TestSingleton instance = new TestSingleton();
}
private TestSingleton() {
}
public static TestSingleton getInstance() {
return SingletonHolder.instance;
}
}
6、懒汉式:枚举
package constxiong.interview;
import java.util.concurrent.atomic.AtomicLong;
/**
* 单例模式 懒汉式-枚举,id生成器
* @author ConstXiong
*/
public enum TestSingleton {
INSTANCE;
private AtomicLong id = new AtomicLong(0);
public long getId() {
return id.incrementAndGet();
}
}
实现方式的选择建议: