Ruby中实例变量的通用Setter实现:Box类场景实践
嘿,我帮你梳理并完善这个Box类的实现,刚好能解决你提到的类变量更新的问题——尤其是@@totalvolume需要在实例属性变化时实时更新的需求:
完整的Box类实现
class Box # 初始化类变量:盒子总数和总体积 @@box_counter = 0 @@total_volume = 0 # 初始化方法:创建盒子实例时触发 def initialize(length, width, height) @length = length @width = width @height = height @@box_counter += 1 # 把当前盒子的体积加入总体积 @@total_volume += volume end # 实例方法:计算单个盒子的体积 def volume @length * @width * @height end # 自定义setter方法:修改length时同步更新总体积 def length=(new_length) # 先减去原来的体积 @@total_volume -= volume @length = new_length # 再加上新的体积 @@total_volume += volume end # 同理实现width和height的setter def width=(new_width) @@total_volume -= volume @width = new_width @@total_volume += volume end def height=(new_height) @@total_volume -= volume @height = new_height @@total_volume += volume end # 类方法:对外暴露盒子总数和总体积 def self.box_counter @@box_counter end def self.total_volume @@total_volume end end
关键逻辑说明
- 类变量初始化:咱们先把
@@box_counter和@@total_volume初始化为0,这俩是所有Box实例共享的全局状态。 - 初始化时的更新:每次创建新盒子,
initialize方法会自动把@@box_counter加1,同时把当前盒子的体积加到@@total_volume里——这里复用了volume方法,避免重复写计算逻辑。 - 自定义Setter的核心作用:如果直接用
attr_writer生成默认的赋值方法,修改属性时不会触发总体积的更新。所以咱们手动写每个属性的setter:先从总体积里减去盒子原来的体积,更新属性后,再把新体积加回去,这样@@total_volume就能实时保持准确。 - 类方法的便利性:添加
box_counter和total_volume这两个类方法,外部可以直接通过Box.box_counter和Box.total_volume查看全局状态,不用去直接访问类变量(符合封装原则)。
测试示例
# 创建两个盒子 box1 = Box.new(2, 3, 4) # 体积24 box2 = Box.new(1, 1, 1) # 体积1 puts Box.box_counter # 输出:2 puts Box.total_volume # 输出:25 # 修改box1的长度 box1.length = 5 # 新体积5*3*4=60,总体积变为60+1=61 puts Box.total_volume # 输出:61 # 修改box2的高度 box2.height = 5 # 新体积1*1*5=5,总体积变为60+5=65 puts Box.total_volume # 输出:65
这样实现后,不管是创建新盒子还是修改已有盒子的尺寸,@@totalvolume都会自动更新,完美满足你的需求~
内容的提问来源于stack exchange,提问作者wintermute
相关产品推荐
相关产品推荐

