lua面向對象的2種私密性封裝

一、返回table

local function  newAccount( initCount)
    local self = { count = initCount}
     set = function( c)
                self.count = c
            end
     get = function( )
                return self.count
           end
        -- body
    return {
    set = set,
    get = get
  }
 end

測試:

local acc =  newAccount(10)
print( acc.get())
acc.set(100)
print( acc.get())

local acc1 = newAccount(20)

print( acc.get())
print( acc1.get())

運行結果

10
100
100
20

二、返回單一的操作函數

local function  newObject( initCount)
    -- body
    return function( opr,v)
            if opr == "get" then
                return initCount
            elseif opr == "set" then
                initCount = v
            else
                print(" unknown opr : "..opr)
            end
    end
end

測試:

local obj = newObject(100)

print(obj("get"))
print(obj("set",30))
print(obj("post"))
print(obj("get"))

運算結果

100

 unknown opr : post

30
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章