在 Ruby 中使用 getter 覆盖方法



下面的代码按预期运行,但是用属性的getter覆盖方法(请参阅下面的代码中的action_label(有什么缺点吗?请参阅代码中的:action_label

class BaseAction
def action_label
raise NotImplementedError
end
def run
puts "Running action: #{action_label}"
yield        
end
end
class SimpleAction < BaseAction  
def initialize(label)    
@action_label = label
end
private
attr_reader :action_label
end
sa = SimpleAction.new("foo")
sa.run {puts "action!"}

attr_reader :action_label只是定义一个方法。Ruby 中的"getter"就是这样的方法

def action_label
@action_label
end

attr_reader是定义这种方法的简写。

在子类中重新定义方法并没有错,这是OOP的一大特性。

这也不是NotImplementError的用途。提出别的东西。

最新更新