Lua Privacy、单方法

2020-03-10  本文已影响0人  86a262e62b0b

Privacy
单方法

一. Privacy

function newAccount ()
    --保存对象状态的table保存在闭包环境下
    local self = {balance = initialBalance}

    local withdraw = function (v)
        self.balance = self.balance - v
    end

    local deposit = function (v)
        self.balance = self.balance + v
    end

    local getBalance = function () return self.balance end

    return {
        withdraw = withdraw,
        deposit = deposit,
        getBalance = getBalance
    }
end

acc1 = newAccount(100.00)
acc1.withdraw(40.00)
print(acc1.getBalance())     --> 60

一. 单方法(The Single-Method Approach)

function newObject (value)
    return function (action, v)
        if action == "get" then return value
            elseif action == "set" then value = v
            else error("invalid action")
        end
    end
end

d = newObject(0)
print(d("get"))    --> 0
d("set", 10)
print(d("get"))    --> 10
上一篇 下一篇

猜你喜欢

热点阅读