Ruby设计模式:

模板方法:定义一个操作中的算法的骨架 而将一些步骤的实现延迟到子类中 模板方法使得之类可以不改变算法的结构既可重定义该算法的某些特定步骤

 
  
  1. #%()用来定义单行字符串 --- 包含“ 并且有字符串插值 
  2. class Report 
  3.   def output; puts "#{report_start}#{report_body}#{report_end}"end 
  4.   def report_body 
  5.     %(\nbody\n) 
  6.   end 
  7. end 
  8.  
  9. class HtmlReport < Report 
  10.   def report_start 
  11.     %(<html>) 
  12.   end 
  13.   def report_end 
  14.     %(</html>) 
  15.   end 
  16. end 
  17.  
  18. class TextReport < Report 
  19.   def report_start 
  20.     %(=start=) 
  21.   end 
  22.  
  23.   def report_end 
  24.     %(=end=) 
  25.   end 
  26. end 
  27.  
  28. TextReport.new.output 
  29. HtmlReport.new.output 

结果:

=start=

body

=end=

<html>

body

</html>