Lua屏蔽对象方法和恢复的方法

背景

对于OO思想实现的类, 对于某些场景需要屏蔽某些方法, 不让调用。过了这段场景, 就恢复这些类的方法, 可以调用。

例如:

工厂具有开工方法, 但是在晚上不允许开工, 所有在晚上这段时间, 见开工方法屏蔽掉, 到第二天早上八点将此方法恢复。

实现

local tab = {
    new = function()
        print("new is called.")
    end,
    delete = function()
        print("delete is called.")
    end,
}


tab.new()
tab.delete()


function setHiddenProperty(tab, name)
    if not tab[name] then
        return
    end

    if not tab.__hiddenProps then
        tab.__hiddenProps = {}
    end

    local hiddenProps = tab.__hiddenProps

    hiddenProps[name] = tab[name]
    tab[name] = nil
end

function restoreHiddenPorpertys(tab)
    local hiddenProps = tab.__hiddenProps

    if not hiddenProps then
        return
    end

    for k,v in pairs(hiddenProps) do
        tab[k] = v
    end

    tab.__hiddenProps = nil
end


setHiddenProperty(tab, "new")
setHiddenProperty(tab, "delete")

-- this time call new and delete will throw error
--tab.new()
--tab.delete()

restoreHiddenPorpertys(tab)

tab.new()
tab.delete()

LOG:

>lua -e "io.stdout:setvbuf 'no'" "luatest.lua"
new is called.
delete is called.
new is called.
delete is called.
>Exit code: 0

原文地址:https://www.cnblogs.com/lightsong/p/5879473.html