返回

unity3d:单例模式,Mono场景唯一,不销毁;C# where T:new(),泛型约束;Lua单例模式,table ,self

发布时间:2023-02-02 19:00:45 225
# c#

Mono单例

  1. 场景里挂载了,先找场景里有的
  2. DontDestroyOnLoad
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

namespace Singleton
{
public abstract class MonoSingleton : MonoBehaviour where T : MonoSingleton
{
protected static T m_instance = null;


public static T instance
{
get
{
if (m_instance == null)
{
string name = typeof(T).ToString();
GameObject gameEntryInstance = GameObject.Find(name); //单例的名字都唯一,防止场景里已经有了
if (gameEntryInstance == null)
{
gameEntryInstance = new GameObject(name);
DontDestroyOnLoad(gameEntryInstance);
}
if (gameEntryInstance != null)
{
m_instance = gameEntryInstance.GetComponent();
}
if (m_instance == null)
{
m_instance = gameEntryInstance.AddComponent();
}
}

return m_instance;
}
}

public void StartUp()
{

}
protected void OnApplicationQuit()
{
m_instance = null;
}
}

}

c#单例

在对泛型的约束中,最常使用的关键字有where 和 new。
其中where关键字是约束所使用的泛型,该泛型必须是where后面的类,或者继承自该类。
new()说明所使用的泛型,必须具有无参构造函数,这是为了能够正确的初始化对象

///
/// C#单例模式
///
public abstract class Singleton where T : class,new()
{
private static T instance;
private static object syncRoot = new Object();
public static T Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new T();
}
}
return instance;
}
}

protected Singleton()
{
Init();
}

public virtual void Init() { }
}

Lua单例

【腾讯文档】XLua中面向对象,多态,重载,私有,单例
​​​ https://docs.qq.com/doc/DWlBsSUljbGZOVFZN​​​ 使用GetInstance访问,每次只返回 唯一的new 的table
在lua中,表拥有一个标识:self。self类似于this指针,大多数面向对象语言都隐藏了这个机制,在编码时不需要显示的声明这个参数,就可以在方法内使用this(例如C++和C#)。在lua中,提供了冒号操作符来隐藏这个参数
Singleton.lua

local function __init(self)
assert(rawget(self._class_type, "Instance") == nil, self._class_type.__cname.." to create singleton twice!")
rawset(self._class_type, "Instance", self)
end

local function __delete(self)
rawset(self._class_type, "Instance", nil)
end

local function GetInstance(self)
if rawget(self, "Instance") == nil then
rawset(self, "Instance", self.New())
end
assert(self.Instance ~= nil)
return self.Instance
end

如何创建

local ResourcesManager = BaseClass("ResourcesManager", Singleton)

 

特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(0)
按点赞数排序
用户头像
精选文章
thumb 中国研究员首次曝光美国国安局顶级后门—“方程式组织”
thumb 俄乌线上战争,网络攻击弥漫着数字硝烟
thumb 从网络安全角度了解俄罗斯入侵乌克兰的相关事件时间线
下一篇
小白如何用Java编写爬虫程序 2023-02-02 18:55:38