public class MySingleton { private static MySingleton instance = null; private MySingleton() { // Private constructor to prevent instantiation outside of this class. } public static MySingleton getInstance() { if (instance == null) { instance = new MySingleton(); } return instance; }},构造函数有private不能实例化,为什么get方法有new MySingleton?
时间: 2023-06-15 17:05:20 浏览: 43
虽然构造函数被声明为私有,但是静态方法 `getInstance()` 可以在该类的内部调用该私有构造函数,因此可以创建该类的唯一实例。因为该类的唯一实例是通过静态方法创建的,所以它可以被所有其他的代码访问。在第一次调用 `getInstance()` 时,由于 `instance` 是空的,所以会创建一个新的 `MySingleton` 对象。在随后的调用中,将返回之前创建的实例。这就是单例模式的核心思想:确保一个类只有一个实例,并提供一个全局访问点。
相关问题
qt 创建单例 .h .cpp形式
以下是一个使用 `.h` 和 `.cpp` 形式实现单例的示例:
MySingleton.h 文件:
```cpp
#ifndef MYSINGLETON_H
#define MYSINGLETON_H
class MySingleton {
public:
static MySingleton* instance();
void doSomething();
private:
MySingleton();
~MySingleton();
static MySingleton* m_instance;
};
#endif // MYSINGLETON_H
```
MySingleton.cpp 文件:
```cpp
#include "MySingleton.h"
MySingleton* MySingleton::m_instance = nullptr;
MySingleton* MySingleton::instance() {
if (m_instance == nullptr) {
m_instance = new MySingleton();
}
return m_instance;
}
void MySingleton::doSomething() {
// ...
}
MySingleton::MySingleton() {}
MySingleton::~MySingleton() {}
```
在其他地方使用 `MySingleton` 时,可以这样调用:
```cpp
MySingleton* singleton = MySingleton::instance();
singleton->doSomething();
```
unity 如何用this表示一个单例模式
在 Unity 中,可以通过以下步骤来实现单例模式:
1. 创建一个新的 C# 脚本文件,例如 MySingleton.cs。
2. 在脚本类中添加一个私有静态变量 instance,用于保存单例的唯一实例。
```
public class MySingleton : MonoBehaviour
{
private static MySingleton instance;
// ...
}
```
3. 在 Awake 方法中检查 instance 是否已被初始化,如果没有,则将当前实例赋值给 instance。
```
private void Awake()
{
if (instance == null)
{
instance = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
}
```
4. 通过静态的 Instance 方法来获取单例的实例。
```
public static MySingleton Instance
{
get { return instance; }
}
```
这样就可以通过 `MySingleton.Instance` 来访问单例的唯一实例了。注意,在使用单例模式时,需要确保在场景中只存在一个实例,可以使用 `DontDestroyOnLoad` 方法来防止场景切换时销毁实例。
相关推荐
![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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)