-- mixin.lua
--[[提供混入机制
示例:
    Execute = mixin(nil, "execute")
    Listener = class(nil, Listener)
备注：
    mixin类似多继承，但是继承强调i'am，而mixin强调i'can.
    mixin无法实例化，必须依附到class上，mixin函数的self都是属主class对象
--]]

local dgetinfo = debug.getinfo
local sformat = string.format
local setmetatable = setmetatable

local mixin_tpls = {}

local function index(mixin, field)
    return mixin.__vtbl[field]
end

local function newindex(mixin, field, value)
    mixin.__vtbl[field] = value
end

local mixinMT = {
    __index = index,
    __newindex = newindex,
}

local function mixin_tostring(mixin)
    return sformat("mixin:%s", mixin.__moudle)
end

-- 接口定义函数
function mixin(...)
    local info = dgetinfo(2, "S")
    local moudle = info.short_src
    local mixin_tpl = mixin_tpls[moudle]
    if not mixin_tpl then
        local mixin = {
            __vtbl = {},
            __default = {},
            __moudle = moudle,
            __methods = {...},
            __tostring = mixin_tostring,
        }
        mixin_tpl = setmetatable(mixin, mixinMT)
        mixin_tpls[moudle] = mixin_tpl
    end
    return mixin_tpl
end
