码迷,mamicode.com
首页 > 其他好文 > 详细

LUA OOP 单例模式实现的 一个 方案

时间:2016-05-01 01:05:16      阅读:380      评论:0      收藏:0      [点我收藏+]

标签:

单例

存在这么一类class, 无论class怎么初始化, 产生的instance都是同一个对象。

 

Code

string.toHTMLCode = function(self)

    return encodeHTML(self)

end

-- Instantiates a class

local function _instantiate(class, ...)

    -- 单例模式,如果实例已经生成,则直接返回

    if rawget(class, "__singleton") then

        -- _G[class]值为本class的实例

        if _G[class] then

            return _G[class]

        end

    end

    local inst = setmetatable({__class=class}, {__index = class})

    if inst.__init__ then

        inst:__init__(...)

    end

    --单例模式,如果实例未生成,则将实例记录到类中

    if rawget(class, "__singleton") then

        if not _G[class] then

            _G[class] = inst

        end

    end

    return inst

end

-- LUA类构造函数

local function class(base)

    local metatable = {

        __call = _instantiate,

        __index = base

    }

    -- __parent 属性缓存父类,便于子类索引父类方法

    local _class = {__parent = base}

    -- 在class对象中记录 metatable ,以便重载 metatable.__index

    _class.__metatable = metatable

    return setmetatable(_class, metatable)

end

 

说明:

使用方法, class继承方式不变

如果给定义的class设置一个 _singleton 为 true, 开启单利模式。

LUA OOP 单例模式实现的 一个 方案

标签:

原文地址:http://www.cnblogs.com/lightsong/p/5449790.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!