单例模式最简单的写法

/**

  • 教程级别

*/

class Singleton1 {

private static _ins: Singleton1

private constructor() { }

static get Ins() {

if (!this._ins) {

  this._ins = new Singleton1()

}

return this._ins

}

}

/**

  • 优化写法

*/

class Singleton2 {

private static _ins: Singleton1

private constructor() { }

static get Ins() {

if (this._ins) {

  return this._ins

}

this._ins = new Singleton2()

return this._ins

}

}

/**

  • 行数最少最简单的写法

*/

class Singleton3 {

private static _ins: Singleton3

private constructor() { }

static get Ins() { return this._ins ?? (this._ins = new Singleton3()) }

}

我都是直接这样写的:
public class A {
public static inst:A = new A();
}
:joy: 不懂就问,我不知道为什么大家都习惯要写个getInst之类的方法。

我是看官方的教程是这样教的,就跟着学的呗

你这个是饿汉式单例模式,不管是否可能用到都会提前创建实例。我的是懒汉式单例模式,只有在需要使用的时机才会实例化,如果用不到就不会实例化,按需实例化。

定义个全局变量 启动时候初始化一下,难道还会出现两个实例?

有可能程序员直接new那个类

你做游戏一般写什么用单例

茴香豆的茴有四种写法

管理类一般用单例

不要纠结
用自己习惯的就行

不管饥还是饱

都有各自优势

直接定义一个全局对象不也挺好 :nerd_face:

嘿嘿 无伤大雅我就喜欢全局 一个app.

可以。我只是想提供一个用最少行数就可以实现的懒汉式单例模式

简单粗暴写法


class GameMangerClass {

}

export const GameSystem = new class GameMangerClass {
}
1赞

放在方法里面获取 ,是在调用的第一次才会初始化实例 对于没有用到的时候 占用内存会更小, 另外,游戏在启动时候会初始化,直接写的话,会被提前初始化,相当于和那些需要提前初始化的实例抢了CPU 和初始化的时间。

我基本上就不用单例,都是直接导入导出居多
也就是:
export class xxMgr{
func(){}
}
import xxMgr from xxMgr;
xxMgr.func();
我的xxMgr 都是全局的,本身就只有一个吧(单场景+多预制件开发的)?