Singleton模式的五种实现
单例模式的特点:
- 单例类只能有一个实例。
- 单例类必须自己创建自己的唯一实例。
- 单例类必须给所有其他对象提供这一实例。 -《Java与模式》
单例类可以是没有状态的,仅用做提供工具性函数的对象。既然是提供工具性函数,也就没有必要创建多个实例。
下面列举单例模式的几种实现:
- 单元素的枚举类型实现Singleton – the preferred approach.enum类型是Jdk1.5引入的一种新的数据类型.其背后的基本想法:通过公有的静态final域为每个枚举常量导出实例的类。因为没有可访问的构造器,枚举类型是真正的final。既不能创建枚举类型实例,也不能对它进行扩张 。枚举类型是实例受控的,是单例的泛型化,本质上是氮元素的枚举 -《Effective Java》P129
- public enum Singleton{
- INSTANCE;
- public void execute(){…}
- public static void main(String[] agrs){
- Singleton sole=Singleton.INSTANCE;
- sole.execute();
- }
- }
- 懒汉式 – Lazy initialization . 构造函数是private,只有通过Singleton才能实例化这个类。
- public class Singleton{
- private volatile static Singleton uniqueInstance=null;
- private Singleton(){}
- public static Singleton getInstance(){
- if(uniqueInstance==null){
- synchronized(Singleton.class){
- if(uniqueInstance==null){
- uniqueInstance=new Singleton();
- }
- }
- }
- return uniqueInstance;
- }
- //other useful methods here
- }
- 饿汉式 – Eager initialization
- public class Singleton{
- private static Singleton uniqueInstance=new Singleton();
- private Singleton(){}
- public static Singleton getInstance(){
- return uniqueInstance;
- }
- }
- static block initialization
- public class Singleton{
- private static final Singleton instance;
- static{
- try{
- instance=new Singleton();
- }catch(IOException e){
- thronw new RuntimeException("an error's occurred!");
- }
- }
- public static Singleton getInstance(){
- return instance;
- }
- private Singleton(){
- }
- }
- The solution of Bill Pugh 。- From wiki <Singleton Pattern> 。通过静态成员类来实现,线程安全。
- public class Singleton{
- //private constructor prevent instantiation from other classes
- private Singleton(){}
- /**
- *SingletonHolder is loaded on the first execution of Singleton.getInstance()
- *or the first access to SingletonHolder.INSTANCE,not befor.
- */
- private static class SingletonHolder{
- public static final Singleton instance=new Singleton();
- }
- private static Singleton getInstance(){
- return SingletonHolder.instance;
- }
- }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构