Lua——实现依赖注入

-- GlobalBinder.lua
GlobalBinder = {}
function GlobalBinder._injectTest()
      return 5
end

-- functions.lua
function binder(binderTable)
    local b = class("Binder")
    binderTable = binderTable or GlobalBinder
    setmetatable(b, {__index = function(t,k)
          if binderTable[k] then
              local res = binderTable[k]()
              t[k] = res  -- 缓存起来,不然每次都要返回值
              return res
          end
    end})
    return b
end

-- testBinder.lua
local testBinder = class("TestBinder", binder())
function testBinder:ctor()
     print(self._injectTest)   -->  5
end
return testBinder

你可能感兴趣的:(Lua——实现依赖注入)