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

存在这么一类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

---- code lua format ------

-- Instantiates a class
local function _instantiate(class, ...)
    -- 抽象类不能实例化
    if rawget(class, "__abstract") then
        error("asbtract class cannot be instantiated.")
    end

    -- 单例模式,如果实例已经生成,则直接返回
    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

            -- 对类对象增加实例获取接口
            class.getInstance = function ( self )
                return _G[class]
            end
            -- 对类对象增加实例销毁
            class.destroyInstance = function ( self )
                return _G[class]
            end
        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

--- Test whether the given object is an instance of the given class.
-- @param object Object instance
-- @param class Class object to test against
-- @return Boolean indicating whether the object is an instance
-- @see class
-- @see clone
function instanceof(object, class)
    local meta = getmetatable(object)
    while meta and meta.__index do
        if meta.__index == class then
            return true
        end
        meta = getmetatable(meta.__index)
    end

    return false
end

使用说明:

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

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

Dmenu = class() -- 菜单类
Dmenu.__singleton = true -- 开启单例模式

使用类创建实例:

local menu = Dmenu()
if Dmenu:getInstance() == menu then
print("true")
end
Dmenu:destroyInstance()
menu:destroyInstance()