dimanche 10 juillet 2016

template method pattern, where to define common used functions

Thanks for your time!

I recently read about template pattern(in Ruby) and want to use this pattern in my codes.

My question is "where to put some commonly used functions".

Say I have TemplateRequestBody, JSONRequestBody and XMLRequestBody as following.

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

In this example, add_new_line_to_tail() would be used by all child classes; escape_double_quotes() would be used only by some of the child classes.

Where should I implement these two functions? In TemplateRequestBody or?

Thanks!

Aucun commentaire:

Enregistrer un commentaire