李明明架构师Sign in

Java singleton 单例模式

liming

单例模式

单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。

单例模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象。

单例模式是一种创建型设计模式,它确保一个类只有一个实例,并提供了一个全局访问点来访问该实例。

单例模式有几种实现形式:

1.懒汉模式

public class Singleton {   private static Singleton instance;   public static Singleton getInstance() {   // 懒惰模式   synchronized (Singleton.class) {   if (instance == null) {   instance = new Singleton();   }   }   return instance;   } }

2.饿汉模式

public class Singleton {   private static Singleton instance = new Singleton();   public static Singleton getInstance() {   return instance;   } } 还可以在表态构造里
public class Singleton {   private static Singleton instance ;   static {   instance = new Singleton();   }     public static Singleton getInstance() {   return instance;   } }

3. 双check

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

==============================

OK,大家有什么不懂的可以加QQ群讨论。

也可以直接在评论区交流

看到会回复。

Q群:559722761

微信群:

group qr

抖音|B站|小红书:李明明-架构师

b站\抖音\youtube\西瓜视频:李明明-架构师

telegrame:

https://t.me/alltechnology_source_code