您的位置:首页 > 编程语言 > Lua

lua中的私密性和单一方法实现

2015-07-22 16:57 288 查看
--[[
1、学习在面向对象 私密性 实现的方式
2、单一方法的做法
思想:两个table 一个是用来表示对象的状态  另一个用来表示状态,接口
我们的table是用第二个接口来实现访问的

像其他语言中的单例(私密性)

]]
function newAccount( initlizedBanlance)
local self = { balance = initlizedBanlance}
local show = function( v )
self.balance = self.balance - v
end

local getBanlance = function()
return self.balance
end

return {

show = show,
getBanlance = getBanlance

}
end

acc = newAccount(200)
print(acc.getBanlance())
acc.show(100)
print(acc.getBanlance())

--单一方法演示(set和get方法)
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"))
d("set",10)
--d:set(10)
print(d("get"))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: