java单例模式实现代码怎么写

avatar
作者
筋斗云
阅读量:0

在Java中实现单例模式有多种方式,以下是其中几种常用的实现方式:

  1. 饿汉式(线程安全):
public class Singleton {     private static Singleton instance = new Singleton();      private Singleton() {}      public static Singleton getInstance() {         return instance;     } } 
  1. 懒汉式(线程不安全):
public class Singleton {     private static Singleton instance;      private Singleton() {}      public static Singleton getInstance() {         if (instance == null) {             instance = new Singleton();         }         return instance;     } } 
  1. 懒汉式(线程安全,双重检查锁定):
public class Singleton {     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;     } } 
  1. 静态内部类(线程安全):
public class Singleton {     private Singleton() {}      private static class SingletonHolder {         private static final Singleton INSTANCE = new Singleton();     }      public static Singleton getInstance() {         return SingletonHolder.INSTANCE;     } } 

以上是几种常用的单例模式实现方式,选择哪种方式取决于具体的需求和线程安全性要求。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!