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.youkuaiyun.com/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

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值