单例设计模式的不同实现方式
类的单例设计模式是指采取一定的方法保证在整个的软件系统中,对某个类只能存在一个实例对象,并且该类只提供一个取得其对象的实例方法(静态方法)。
1.饿汉式
1-1:饿汉式(静态常量)
该方式在类装载时候完成实例化,避免线程同步问题,如果自始至终未使用,会造成内存资源的浪费。
class Singleton{
//构造器私有化
private Singleton(){
}
//类内部创建实例
private final static Singleton instance = new Singleton();
//获取实例
public static Singleton getInstance(){
return instance;
}
}
1-2:饿汉式(静态代码块)
优缺点同上
class Singleton {
//构造器私有化
private Singleton() {
}
private static Singleton instance;
//类内部创建对象
static{
instance = new Singleton();
}
//返回实例对象
public static Singleton getInstance(){
return instance;
}
}
2.懒汉式
2-1:懒汉式(线程不安全)
能够解决饿汉式资源浪费问题,但是只能在单线程中使用,在实际开发中存在多线程环境,会存在线程安全问题,不要使用此方式。
class Singleton {
//构造器私有化
private Singleton() {
}
private static Singleton instance;
//提供一个人静态公有方法,使用时才创建instance
public static Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}
2-2:懒汉式(线程安全的)
解决了线程不安全问题,但是每个线程在执行getInstance()方法时都要进行同步,效率太低,在实际开发中不推荐。
class Singleton {
//构造器私有化
private Singleton() {
}
private static Singleton instance;
//提供一个人静态公有方法,使用时才创建instance,加入了同步处理代码synchronized,解决线程安全问题
public static synchronized Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}
3.双重检查
为了既解决线程安全问题,又解决效率低下的问题,可以采用如下方式,推荐使用。
class Singleton {
//构造器私有化
private Singleton() {
}
private static volatile Singleton instance;
//提供一个人静态公有方法,使用时才创建instance,加入了同步处理代码,解决线程安全问题
public static Singleton getInstance(){
if(instance == null){
synchronized (Singleton.class){
if(instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}
4.静态内部类实现
线程安全,节约资源,推荐使用
class Singleton {
//构造器私有化
private Singleton() {
}
private static class SingleInstance{
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance(){
return SingleInstance.INSTANCE;
}
}
5.枚举实现
能够避免多线程同步问题,还能防止反序列化重新创建新的对象,推荐使用。
enum Singleton{
INSTANCE;
public void method(){
}
}