gpt4 book ai didi

ruby - 从父类(super class)调用子类方法 - 设计模式

转载 作者:数据小太阳 更新时间:2023-10-29 08:37:20 25 4
gpt4 key购买 nike

我被困在这里,因为我担心从父类调用子类的类方法是否是最佳实践?

module Zoo

class Animals
class << self
def update
if self.whatever == ... # Calls method 'whatever' from Tiger class
# do sth.
end
end
end
end

class Tiger < Animals
def update
super
end
class << self
def whatever
"whatever from tiger class"
end
end
end
end

Zoo::Tiger.update

它有效,但我将不胜感激任何更好的解决此问题的方法。与某些自定义 hack 不同,我希望尽可能遵循最佳实践解决方案。

提前致谢!

最佳答案

这是一个非常正常的模式。然后,您可以在每个子类中以不同方式实现 whatever,而不必在每个子类中重新实现 update。我要补充的是:

def self.whatever
raise NotImplementedError, 'Class must implement whatever' # or some useful message
end

Animal 类。这样,如果您从未实现 whatever 的子类调用 ChildClass.update,您会得到一个有用的错误。

关于ruby - 从父类(super class)调用子类方法 - 设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28564897/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com