function my.addInstance(cls)
local instance = '_instance'
rawset(cls, instance, nil)
function cls:getInstance(...)
if not rawget(self, instance) then
rawset(self, instance, self:create(...))
end
return rawget(self, instance)
end
function cls:isInstanceExist()
return rawget(self, instance) ~= nil
end
function cls:removeInstance()
rawset(self.class, instance, nil)
end
end
在定义类的地方(定义一个TestModel表,设置过其元表)
my.addInstance(TestModel)
要使用TestModel单例的任意地方
local ModelInstance = mymodel('TestModel'):getInstance()
另mymodel函数实现如下
local cc_loaded_packages=cc.loaded_packages
local function mymodel(modelname)
local model=cc_loaded_packages[modelname]
if(model)then
return model
else
model=import(models.'..modelname)
cc.register(modelname,model)
return model
end
end
function cc.register(name, package)
cc.loaded_packages[name] = package
end
以上有个注意点:
rawset
rawget
根据参数table和index获得真正的值table[index],也就是说根本不会调用到元表,其中参数table必须是一个表,而参数index可以使是任何值。
(个人理解:TestModel是利用元表属性模拟的一个类,且TestModel是个表Table,且设置过元表元方法)
rawget(self, instance),由于self是一个表TestModel,获取instance= '_instance’这个键时,如果没有rawget,则TestModel存在元表,可能获取到其元表的instance)