--[[
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"))
lua中的私密性和单一方法实现
最新推荐文章于 2022-12-30 12:41:38 发布