单例模式与多例模式的创建及使用。
时间: 2024-05-10 16:17:42 浏览: 18
单例模式是一种创建型设计模式,它确保一个类只有一个实例,并提供对该实例的全局访问点。这种模式是通过将类的构造函数设为私有来实现的,从而防止外部代码使用 new 操作符直接实例化对象,而是通过类中的静态方法获取唯一实例。
以下是单例模式的示例代码:
```java
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
```
多例模式是一种创建型设计模式,它允许一个类有多个实例,并提供对这些实例的全局访问点。这种模式是通过在类中维护一个有限数量的实例来实现的,每个实例都有一个唯一的标识符。
以下是多例模式的示例代码:
```java
public class Multiton {
private static final Map<String, Multiton> instances = new HashMap<>();
private Multiton() {}
public static synchronized Multiton getInstance(String key) {
if (!instances.containsKey(key)) {
instances.put(key, new Multiton());
}
return instances.get(key);
}
}
```
在上面的示例代码中,Multiton 类维护了一个 Map,其中包含了所有的实例。getInstance 方法接受一个 key 作为参数,根据这个 key 来获取相应的实例。如果没有找到对应的实例,则创建一个新的实例并将其加入到 Map 中。由于 getInstance 方法是同步的,因此多线程访问时也可以保证每个实例都是唯一的。
相关推荐
![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_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)