require "Class"
CharacterManager = Class:new(nil)
local this = CharacterManager
function this:GetInstance()
if nil == self.m_Instance then
self.m_Instance= self:new()
end
return m_Instance
end
local cm1 = CharacterManager:GetInstance()
local cm2 = CharacterManager:GetInstance()
if(cm1 == cm2) then
print("cm1 == cm2")
end
require “Class” 为 上一篇文章中的基类 Class()http://blog.csdn.net/ywjun0919/article/details/50602904
该方法实现简单,但是 使用new()创建的对象 并不是唯一的,不能保证该类只有一个对象。
使用下面方法可以实现 对象只有一个
require "Class"
CharacterManager = Class:new(nil)
local this = CharacterManager
local Instance = nil
function this:new()
if(nil == Instance) then
Instance = {}
setmetatable(Instance,self)
this:__new()
end
return Instance
end
function this:__new()
self.x = 1
end
function this:GetInstance()
if nil == this.Instance then
this.Instance= this:new()
end
return Instance
end