设计模式中的模板方法模式在Ruby中的应用实例两则

2019-09-25 09:38:37王旭

实例一
今天你还是像往常一样来上班,一如既往地开始了你的编程工作。
项目经理告诉你,今天想在服务器端增加一个新功能,希望写一个方法,能对Book对象进行处理,将Book对象的所有字段以XML格式进行包装,这样以后可以方便与客户端进行交互。并且在包装开始前和结束后要打印日志,这样方便调试和问题定位。
没问题!你觉得这个功能简直是小菜一碟,非常自信地开始写起代码。
Book对象代码如下:

class Book 
 attr_accessor :book_name, :pages, :price, :author, :isbn 
end 

然后写一个类专门用于将Book对象包装成XML格式:

class Formatter 
 
 def format_book(book) 
  puts "format begins" 
  result = "<book_name>#{book.book_name}</book_name>n" 
  result += "<pages>#{book.pages}</pages>n" 
  result += "<price>#{book.price}</price>n" 
  result += "<author>#{book.author}</author>n" 
  result += "<isbn>#{book.isbn}</isbn>n" 
  puts "format finished" 
  result 
 end 
 
end 

 
调用代码如下:

book = Book.new 
book.book_name = "Programming Ruby" 
book.pages = 830 
book.price = 45 
book.author = "Dave Thomas" 
book.isbn = "9787121038150" 
formatter = Formatter.new 
result = formatter.format_book(book) 
puts result 

你写好了之后,迫不及待地开始运行,运行结果也完全符合你的期望。

2016316160008180.png (357×125)

项目经理看完后,对你非常满意,小伙效率很高的嘛!你也非常的得意。
不过两天之后,项目经理又找到了你,他说之前没有考虑到需要交互的客户端还包括手机设备,而手机设备都比较吃流量,用XML格式来传输太耗流量了,想最好能改成使用JSON格式传输。但是之前的XML格式也要保留,最好可以由客户端指定使用哪种格式。
你有些不开心,心里低估着,为什么一开始不考虑周全呢,现在又要改遗留代码。但对方毕竟是领导,你还是要服从命令的,于是你开始修改Formatter类:

class Formatter 
 
 def format_book(book, format) 
  puts "format begins" 
  result = "" 
  if format == :xml 
   result += "<book_name>#{book.book_name}</book_name>n" 
   result += "<pages>#{book.pages}</pages>n" 
   result += "<price>#{book.price}</price>n" 
   result += "<author>#{book.author}</author>n" 
   result += "<isbn>#{book.isbn}</isbn>n" 
  elsif format == :json 
   result += "{n" 
   result += ""book_name" : "#{book.book_name}",n" 
   result += ""pages" : "#{book.pages}",n" 
   result += ""price" : "#{book.price}",n" 
   result += ""author" : "#{book.author}",n" 
   result += ""isbn" : "#{book.isbn}",n" 
   result += '}' 
  end 
  puts "format finished" 
  result 
 end 
 
end