使用java写一个懒汉的单例模式
时间: 2023-06-26 09:08:19 浏览: 56
懒汉式单例模式是指在需要时才去创建类实例,而不是在类加载时就创建实例。以下是使用 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写一个懒汉单例模式线程安全
代码示例如下:
```
public class LazySingleton {
private static LazySingleton instance;
private LazySingleton() {}
public static synchronized LazySingleton getInstance() {
if (instance == null) {
instance = new LazySingleton();
}
return instance;
}
}
```
在这个懒汉模式的单例中,构造函数被声明为私有,确保只能通过getInstance()方法获取单例实例。在第一次调用getInstance()时,instance对象将被实例化。由于该方法使用了synchronized关键字,保证了线程安全。
使用java编写一个懒汉式单例模式
懒汉式单例模式是指在首次调用获取实例方法时才创建实例的单例模式。以下是一个使用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,则直接返回已有的实例。因此,这个实现是懒加载的,只有在需要时才会创建实例。