zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    手机APP漏洞
    测试用例的优先级的概念
    测试出现BUG的理论逻辑
    django-redis 中文文档
    DRF单表序列化和反序列化
    事件
    QT文件操作
    一道字符串题目
    明日方舟六星出货率
    简易图片查看器
  • 原文地址:https://www.cnblogs.com/lightsong/p/5879473.html
Copyright © 2011-2022 走看看