欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 金融 > 单例模式解析

单例模式解析

2024/10/24 23:18:38 来源:https://blog.csdn.net/weixin_46624670/article/details/142078743  浏览:    关键词:单例模式解析

1.什么是单例模式

一种常用的软件设计模式,它确保一个类仅有一个实例,并提供一个全局访问点来获取这个实例。

2.单例模式存在原因

(1)确保一个类仅有一个实例,并提供一个全局访问点来获取这个实例
(2)用于控制资源访问、管理共享资源(如配置文件、数据库连接等)或实现一个全局服务等多种场景。

3.如何实现一个单例模式

(1)私有构造方法
防止外部通过new关键字创建类的实例。
(2)私有静态实例
在类内部创建一个类的唯一实例,并将其声明为静态变量。
(3)公共静态方法
提供一个公共的静态方法,返回类的唯一实例,并在需要时创建这个实例。

4.具体方案:

懒汉式(线程不安全)

public class Singleton {  private static Singleton instance;  private Singleton() {}  public static Singleton getInstance() {  if (instance == null) {  instance = new Singleton();  }  return instance;  }  
}

懒汉式(线程安全)

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

双重检查锁定(Double-Checked Locking)

public class Singleton {  // volatile关键字确保多线程的可见性和禁止指令重排序  private static volatile Singleton instance;  private Singleton() {}  public static Singleton getInstance() {  if (instance == null) {  synchronized (Singleton.class) {  if (instance == null) {  instance = new Singleton();  }  }  }  return instance;  }  
}

静态内部类

public class Singleton {  private Singleton() {}  private static class SingletonHolder {  private static final Singleton INSTANCE = new Singleton();  }  public static final Singleton getInstance() {  return SingletonHolder.INSTANCE;  }  
}

枚举

public enum Singleton {  INSTANCE;  public void whateverMethod() {  }  
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com