TS的泛型单例模板(已解决)

您给我的好像不是单例模板(泛型单例),我参照官方写了一个,但是NetMgr.Instance().; //这里无法调用到NetMgr.ts中的方法Hello()。这是为什么?

代码如下:
import { _decorator, Component, Node } from “cc”;
const { ccclass, property } = _decorator;

@ccclass(“SingletonPattern”)
export default class SingletonPattern {

private static instance:any=null;
public static Instance(type:{new ():T}){
if(this.instance==null){
this.instance=new type();
}
return this.instance;
}

}

继承自单例模板:
import { _decorator, Component, Node } from “cc”;
import SingletonPattern from “./Help/SingletonPattern”;
const { ccclass, property } = _decorator;

//这个脚本用于对网络服务的管理
@ccclass(“NetMgr”)
export class NetMgr extends SingletonPattern< NetMgr> {
//可能会单独把微信开放域相关的代码放在另一个脚本
//而这个脚本则是对这个进行管理

public Log()
{
    console.log("单例模板成功使用");
}

}

调用单例子类的方法:
import { _decorator, Component, Node } from “cc”;
const { ccclass, property } = _decorator;

import{ UIMgr } from “./UIMgr”;
import{NetMgr} from “./NetMgr”;

//这个脚本负责游戏逻辑
@ccclass(“GameMgr”)
export class GameMgr extends Component {
//游戏初始化、场景跳转
//游戏结算等
//使用中介者模式

@property
public isCross:boolean;

@property
public Score=0;//得分

/**
 * 计算得分
 */
public CalScore() {
    //是否穿过平台
    if (this.isCross = true) {
        this.Score += 1;
    }
}
   

/**
 * 游戏结束
 */
public GameOver() {
    //结算奖励

    //返回主界面
    NetMgr.Instance().; //这里无法调用。
   
    UIMgr.Instance().SetAcitve();

    console.log("游戏结束");
}

}

大佬,还有个问题,能解答一下吗?就是单例模板/泛型单例的问题。

简单单例模式

官方单例模板?你哪儿找的?如果你自己真的有需求用到高级的ts特性,建议你还是完整的看看ts语法。否则后面估计会遇到更多问题

export class Singleton{
private static instance: any = null;
public static Instance(c: { new(): T }): T {
if (this.instance == null) {
this.instance = new c();
}
return this.instance;
}

public Update(dt: number) {

}

}
只能帮到你这

cocos论坛里,有个帖子叫泛型单例。

你这个就直接报错了。

你就不会改一下加个???

这样写…???好像可以



我这么写不行,我的子类不是继承自Component了。

把T替换成Component也是不行的。

这样写也不行。

汗:sweat_smile:

这是解决了吗。。

1赞

你要明白单例是什么,确保全局只有一个。这是写的方法又很多,切换场景后,你还要确定单例只有一个这个要加一个if判断,我只是写了一个最最最简单的给你,高端的又怕你看不懂。。。其实就跟C#转过来一样,又空你去看下ts 的语法,其实出入不大的,只要你自己可以看的明白

你觉得你应该把那些语法弄懂一下

嗯,我翻了TS官方文档,但是不好找。刚接触TS没几天,很多懵逼。
你说“切换场景后,你还要确定单例只有一个这个要加一个if判断”,我不太理解。

不错,是的。

算了,等你考虑性能这一方面,你就知道我说什么了~

用单例就是要考虑性能,大佬若方便指点一下,:cry:或者能推荐一下博客之类的。。。

你去查一下C#的高级单例,你就明白!

if(s_instance == null){}这句。。。