Cocos Creator如何编写单例模式
时间: 2023-10-03 07:08:35 浏览: 52
在 Cocos Creator 中,可以通过 JavaScript 的类来实现单例模式。以下是一个简单的单例模式示例:
```javascript
class Singleton {
constructor() {
if (!Singleton.instance) {
Singleton.instance = this;
}
return Singleton.instance;
}
hello() {
console.log("Hello, I'm a singleton!");
}
}
export default Singleton;
```
在这个示例中,我们定义了一个名为 Singleton 的类,并使用 constructor 方法来实现单例模式。当第一次创建 Singleton 类的实例时,我们将把这个实例存储在静态属性 instance 中。当再次创建 Singleton 类的实例时,我们返回已经存在的实例,而不是创建一个新的实例。
要使用单例模式,只需要在需要的地方导入 Singleton 类并创建一个新的实例即可:
```javascript
import Singleton from "./Singleton";
const instance1 = new Singleton();
const instance2 = new Singleton();
console.log(instance1 === instance2); // true
instance1.hello(); // 输出 "Hello, I'm a singleton!"
instance2.hello(); // 输出 "Hello, I'm a singleton!"
```
在这个示例中,我们创建了两个 Singleton 类的实例,但它们实际上是同一个实例。这是因为我们使用单例模式确保只有一个实例存在。
相关推荐
![ts](https://img-home.csdnimg.cn/images/20210720083646.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)