下面的代码按预期运行,但是使用属性的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中的“getters”就是这样的方法
def action_label
@action_label
end
attr_reader
是定义这种方法的简写。
重新定义子类中的方法没有任何问题,这是OOP的一大特色。
这也不是NotImplementedError的用途。提高别的东西。