lua实现伪多态继承

通过lua的设置元表__index字段,巧妙的运用在无法索引到对象的key时会调用__index的机制,实现了伪多态、继承。
代码如下:

inheritance = {}
_classTotalTable = {}

function inheritance:class(father)
    local classVo = {}
    classVo.constructor = false --构造函数
    classVo.father = father  --父类
    classVo.new = function(...)
        local obj = {}
        setmetatable(obj,{__index = _classTotalTable[classVo]})
        local create
        create = function(c,...)
            if c.father then
                create(c.father,...)
            end
            if c.constructor then
                c.constructor(obj,...)
            end 
        end
        create(classVo,...)
        return obj
    end

    local virtualTable = {}

    -- tip:当经过此继承代码return的对象增加成员变量时,放入虚表
    _classTotalTable[classVo] = virtualTable
    setmetatable(classVo,{__newindex = 
        function(table,key,value)
            virtualTable[key] = value
        end
    })
    -- tip:索引不到对应key调用__index
    -- 索引虚表,父类有此值,给予子类
    if father then
        setmetatable(virtualTable,{__index = 
        function (table,key)
            local ret = _classTotalTable[father][key]
            virtualTable[key] = ret
            return ret
        end
        })
    end

    return classVo
end

--使用事例
baseClass = inheritance:class()

function baseClass:constructor()
    print("base:constructor")   
end

function baseClass:wowo()
    print("base:wowo")      
end

sonClass = inheritance:class(baseClass)

function sonClass:constructor()
    print ("son:constructor")   
end

function sonClass:wowo()
    print("son:wowo")   
end

newson = sonClass:new() --base:constructor   --son:constructor


newson:wowo()   --son:wowo
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值