使用java编写一个懒汉式单例模式
时间: 2024-04-09 15:09:17 浏览: 9
懒汉式单例模式是指在首次调用获取实例方法时才创建实例的单例模式。以下是一个使用Java编写的懒汉式单例模式的示例:
```
public class SingletonLazy {
private static SingletonLazy instance;
private SingletonLazy() {}
public static SingletonLazy getInstance() {
if (instance == null) {
instance = new SingletonLazy();
}
return instance;
}
}
```
在这个示例中,私有构造函数确保只能通过getInstance()方法获取实例。getInstance()方法使用instance变量来存储实例,并在首次调用时创建实例。如果instance变量不为null,则直接返回已有的实例。因此,这个实现是懒加载的,只有在需要时才会创建实例。
相关问题
使用java写一个懒汉的单例模式
懒汉式单例模式是指在需要时才去创建类实例,而不是在类加载时就创建实例。以下是使用 Java 语言编写的懒汉式单例模式的示例代码:
```java
public class LazySingleton {
// 私有静态变量,用于记录唯一实例
private static LazySingleton instance;
// 私有构造函数,确保外部无法通过构造函数创建实例
private LazySingleton() {}
// 公有静态方法,用于获取唯一实例
public static LazySingleton getInstance() {
if (instance == null) {
instance = new LazySingleton();
}
return instance;
}
}
```
在上述代码中,私有静态变量 `instance` 用于记录唯一实例,初始值为 `null`。公有静态方法 `getInstance()` 用于获取唯一实例,如果当前实例为 `null`,则创建一个新的实例并将其赋值给 `instance`,否则直接返回 `instance`。由于构造函数是私有的,因此外部无法通过构造函数创建实例,只能通过静态方法获取唯一实例。
使用java写一个单例模式
你好,以下是使用 Java 编写单例模式的示例代码:
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
这是一个线程安全的懒汉式单例模式,getInstance() 方法返回唯一的实例。