现在我正在使用实施 OOP 的闭包 http://lua-users.org/wiki/ObjectOrientationClosureApproach在卢阿。下面是一个简短的示例。我的问题发生在尝试实施时stronger_heal
inside infested_mariner
.
--------------------
-- 'mariner module':
--------------------
mariner = {}
-- Global private variables:
local idcounter = 0
local defaultmaxhp = 200
local defaultshield = 10
function mariner.new ()
local self = {}
-- Private variables:
local hp = maxhp
-- Public methods:
function self.sethp (newhp)
hp = math.min (maxhp, newhp)
end
function self.gethp ()
return hp
end
function self.setarmorclass (value)
armorclass = value
updatearmor ()
end
return self
end
-----------------------------
-- 'infested_mariner' module:
-----------------------------
-- Polymorphism sample
infested_mariner = {}
function infested_mariner.bless (self)
-- New methods:
function self.strongerheal (value)
-- how to access hp here?
hp = hp + value*2
end
return self
end
function infested_mariner.new ()
return infested_mariner.bless (mariner.new ())
end
如果我把我的infested_mariner
如果在另一个 .lua 文件中定义,它将无法访问全局私有变量,也无法访问基本 .lua 文件中定义的私有变量。我如何保护仅infested_mariner
可以访问,并且解决方案不涉及将所有派生类与父类放在同一个文件中?
注意:我目前在子类中使用 getter 和 setter。
这是封闭方法的限制。没有办法访问hp
从封闭外部。
这是一种意识形态问题......有些人说受保护的成员破坏了封装,因此应该避免它们:将所有数据设为私有,并在需要时扩展接口(添加公共功能)。说这句话的人往往喜欢封闭方法。
如果你想使用受保护的成员,我可能会not使用闭包方法。良好的命名约定可能是最简单的事情。
self.public_thing = "asdf"
self._protected_thing = "asdf"
当然,数据实际上是公开的,但这种方法效果很好。这几乎就是 Python 所做的事情。当您想要搞乱内部结构(例如测试)时,它会派上用场。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)