Lua单例(lua学习二)

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

这里写图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Lua 中,可以使用闭包(closure)的方式来实现单例模式。单例模式指的是一个类只能创建一个实例,并提供一个全局的访问点来访问该实例。下面是一个使用闭包实现单例模式的示例: ```lua local Singleton = (function() -- 私有变量和方法 local instance = nil local privateMethod = function() print("This is a private method.") end -- 单例对象 local Singleton = {} -- 对外接口 function Singleton.getInstance() if not instance then instance = setmetatable({}, { __index = Singleton }) end return instance end function Singleton:publicMethod() print("This is a public method.") end return Singleton end)() -- 获取单例实例 local instance1 = Singleton.getInstance() local instance2 = Singleton.getInstance() -- 输出 true,说明 instance1 和 instance2 是同一个对象 print(instance1 == instance2) ``` 在上面的示例中,我们使用了一个立即调用的匿名函数来创建一个闭包。在闭包内部,我们定义了一个私有变量 `instance` 和一个私有方法 `privateMethod`,这些变量和方法只能在闭包内部被访问。 然后,我们创建了一个单例对象 `Singleton`,并提供了一个对外接口 `getInstance()` 来获取单例实例。在 `getInstance()` 函数中,如果实例不存在,则创建一个新的实例,并使用元表(metatable)来指定其原型为 `Singleton` 对象,以便可以调用 `Singleton` 对象中的方法和属性。 最后,我们在全局范围内获取了两个单例实例 `instance1` 和 `instance2`,并使用 `==` 运算符比较它们是否相等,结果为 true,说明它们是同一个对象。 通过使用闭包和元表,我们可以实现一个简单的单例模式。需要注意的是,单例模式可能会导致全局状态的共享和复杂度的增加,因此需要谨慎使用。同时,也可以考虑使用其他的设计模式来替代单例模式,以便更好地管理对象和状态。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值