Ruby 模板方法模式,在其中定义常用函数

Ruby 模板方法模式,在其中定义常用函数,ruby,templates,design-patterns,Ruby,Templates,Design Patterns,谢谢你的时间 我最近阅读了有关模板模式(Ruby)的文章,并希望在代码中使用该模式 我的问题是“在哪里放置一些常用函数” 假设我有TemplateRequestBody、JSONRequestBody和XMLRequestBody,如下所示 class TemplateRequestBody def pretty_format raised "called abstract method: pretty_format" end end class JSONRequestBody

谢谢你的时间

我最近阅读了有关模板模式(Ruby)的文章,并希望在代码中使用该模式

我的问题是“在哪里放置一些常用函数”

假设我有TemplateRequestBody、JSONRequestBody和XMLRequestBody,如下所示

class TemplateRequestBody
  def pretty_format
    raised "called abstract method: pretty_format"
  end
end

class JSONRequestBody < TemplateRequestBody
  def pretty_format
    # pretty format JSON
    add_new_line_to_tail();
  end
end

class XMLRequestBody < TemplateRequestBody
  def pretty_format
    # pretty format XML
    escape_double_quotes();
    add_new_line_to_tail();
  end
end
类TemplateRequestBody
def格式
提出“被调用的抽象方法:pretty_格式”
结束
结束
类JSONRequestBody
在本例中,
add_new_line_to_tail()
将被所有子类使用<代码>转义双引号()
将仅由某些子类使用

我应该在哪里实现这两个功能?在TemplateRequestBody还是


谢谢

一如既往-这取决于:)

如果一个方法将在子类之间共享,那么将它放在父类(
TemplateRequestBody
)中是有意义的。如果这些方法不会在子类之间共享,那么就不要把它们放在一起

如果某些类将使用该方法,您可能会想,mixin是否是存储该方法的好地方?此外,将其放在父类中也不是一个糟糕的主意


希望有帮助

你可以使用Ruby内置的
NotImplementedError
raisenotimplementederror.new('pretty\u format')
谢谢@Ile Eftimov提供这些信息!我以前不知道这个想法。不知羞耻的插件:我写过关于Ruby和模板方法模式的博客,你们可以查看:)很棒的博客!非常感谢:)