用Java写一个懒汉模式代码
时间: 2023-06-01 22:03:44 浏览: 49
public class LazySingleton {
private static LazySingleton instance;
private LazySingleton() {}
public static LazySingleton getInstance() {
if (instance == null) {
instance = new LazySingleton();
}
return instance;
}
}
相关问题
用java写一个懒汉模式
的单例模式。
好的,我可以帮你回答这个问题。
懒汉模式的单例模式是指,在需要使用单例实例时才会创建,而不是在类加载时就创建。以下是用Java实现懒汉模式单例模式的代码:
```java
public class SingletonLazy {
private static SingletonLazy instance = null;
private SingletonLazy() {
}
public static SingletonLazy getInstance() {
if (instance == null) {
instance = new SingletonLazy();
}
return instance;
}
}
```
在该实现中,私有构造函数保证了该类无法通过其他途径被实例化。getInstance()方法首次调用时会实例化SingletonLazy类,随后每次调用返回的都是同一个实例。同时,如果该方法被多线程同时调用时,需要加上synchronized关键字来保证线程安全。
用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关键字,保证了线程安全。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)