手机
当前位置:查字典教程网 >脚本专栏 >ruby专题 >设计模式中的模板方法模式在Ruby中的应用实例两则
设计模式中的模板方法模式在Ruby中的应用实例两则
摘要:实例一今天你还是像往常一样来上班,一如既往地开始了你的编程工作。项目经理告诉你,今天想在服务器端增加一个新功能,希望写一个方法,能对Book...

实例一

今天你还是像往常一样来上班,一如既往地开始了你的编程工作。

项目经理告诉你,今天想在服务器端增加一个新功能,希望写一个方法,能对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

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

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

项目经理看完后,对你非常满意,小伙效率很高的嘛!你也非常的得意。

不过两天之后,项目经理又找到了你,他说之前没有考虑到需要交互的客户端还包括手机设备,而手机设备都比较吃流量,用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

调用代码如下:

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, :xml) puts result result = formatter.format_book(book, :json) puts result

再次运行程序,得到了以下结果。

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

项目经理看到运行结果后开心地说:“太好了,这正是我想要的!”

可是你这次却没有那么开心,你觉得代码已经有些混乱了,XML格式的逻辑和JSON格式的逻辑混淆在一起,非常不利于阅读,而且如果以后还需要扩展功能也会非常困难。好在传输格式一般也就XML和JSON了,应该不会再有什么扩展了,你这样安慰自己道。

但幻想总会被现实打破,“我最近听说有个YAML格式挺好玩的.......” 项目经理说道。这个时候你已经有想打人的冲动了!!!

很多时候就是这样,在公司里写的代码乱七八糟,质量极差,很大一部分原因就是因为需求变来变去。我们不断在原有代码基础上补充各种后续加入的情况,在一行行新增的if语句下面,我们的代码变得不堪入目。当然,我们作为程序员,对于需求这种东西没有太多的话语权,在这方面我们无能为力。但是我们可以尽量地把程序的架构设计好,让我们写出的代码更具有扩展性,这样就可以应对各种需求变更了。

下面你将要使用23种设计模式中的模板方法来改进以上程序。

首先要定义专门的子类来处理每种传输格式的具体逻辑,这样不同传输格式的逻辑可以从一个方法里分离开,明显便于阅读和理解。

定义类XMLFormatter继承自Formatter,里面加入处理XML格式的具体逻辑:

class XMLFormatter < Formatter def formating(book) 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" end end

定义类JSONFormatter继承自Formatter,里面加入处理JSON格式的具体逻辑:

class JSONFormatter < Formatter def formating(book) 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 end

然后将Formatter中的代码进行修改,如下所示:

class Formatter def format_book(book) before_format result = formating(book) after_format result end def before_format puts "format begins" end def formating(book) raise "You should override this method in subclass." end def after_format puts "format finished" end end

你会发现format_book方法只有四步,第一步调用before_format,去打印格式转换前的日志。第二步调用formating,处理具体的转换逻辑,但是formating方法中只是raise了一个异常,因为具体的转换的逻辑应该由子类来处理,如果走到了父类的formating方法中,就说明应该出现异常。第三步调用after_format,去打印格式转换后的日志。第四步返回result。

最后调用代码如下:

book = Book.new book.book_name = "Programming Ruby" book.pages = 830 book.price = 45 book.author = "Dave Thomas" book.isbn = "9787121038150" xmlFormatter = XMLFormatter.new result = xmlFormatter.format_book(book) puts result jsonFormatter = JSONFormatter.new result = jsonFormatter.format_book(book) puts result

运行之后,你会发现运行结果和修改前代码的运行结果完全相同。但是使用模板方法之后,代码的可读性有了很大的提高,因为处理格式转换的代码都放到了各自的类当中,而不是全部塞进一个方法中。并且在扩展性上也有了很大的提升,比如你开始感兴趣项目经理说的YAML格式了。

定义类YAMLFormatter继承自Formatter,里面加入处理YAML格式的具体逻辑:

class YAMLFormatter < Formatter def formating(book) 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" end end

调用代码只需要加入:

yamlFormatter = YAMLFormatter.new result = yamlFormatter.format_book(book) puts result

好了,令人头疼的YAML格式就这样被支持了,只需要在调用的时候决定是实例化XMLFormatter,JSONFormatter还是YAMLFormatter,就可以按照相应的规格进行格式转换了。而且整体的代码很有条理,看起来也很舒心。这个时候,你会轻松地向项目经理调侃一句,还有需要支持的格式吗?

实例二

需求:

学生抄题目,做题目

初始代码

# -*- encoding: utf-8 -*- #学生甲的试卷类 class TestPaperA def question1 puts '杨过得到,后来给了郭靖,炼成倚天剑,屠龙刀的玄铁可能是[] a.球墨铸铁 b.马口铁 c.高速合金钢 d.碳塑纤维 ' puts '答案:b' end def question2 puts '杨过、程英、陆无双铲除了情花,造成了[] a.使这种植物不再害人 b.使一种珍稀物种灭绝 c.破坏了那个生物圈的生态平衡 d.造成该地区沙漠化 ' puts '答案:a' end def question3 puts '蓝凤凰的致使华山师徒、桃谷六仙呕吐不止,如果你是大夫,会给他们开什么药[] a.阿司匹林 b.牛黄解毒片 c.氟酸 d.让他们喝大量的生牛奶 e.以上全不对' puts '答案:c' end end #学生乙的试卷类 class TestPaperB def question1 puts '杨过得到,后来给了郭靖,炼成倚天剑,屠龙刀的玄铁可能是[] a.球墨铸铁 b.马口铁 c.高速合金钢 d.碳塑纤维 ' puts '答案:d' end def question2 puts '杨过、程英、陆无双铲除了情花,造成了[] a.使这种植物不再害人 b.使一种珍稀物种灭绝 c.破坏了那个生物圈的生态平衡 d.造成该地区沙漠化 ' puts '答案:b' end def question3 puts '蓝凤凰的致使华山师徒、桃谷六仙呕吐不止,如果你是大夫,会给他们开什么药[] a.阿司匹林 b.牛黄解毒片 c.氟酸 d.让他们喝大量的生牛奶 e.以上全不对' puts '答案:a' end end puts '学生甲抄的试卷' student1 = TestPaperA.new student1.question1 student1.question2 student1.question3 puts '学生乙抄的试卷' student2 = TestPaperB.new student2.question1 student2.question2 student2.question3

存在的问题:

TestPaperA和TestPaperB中的代码很多相同的地方,不利于维护,如果需要修改题目的话,就要改两处

改后的代码

# -*- encoding: utf-8 -*- class TestPaper def question1 puts '杨过得到,后来给了郭靖,炼成倚天剑,屠龙刀的玄铁可能是[] a.球墨铸铁 b.马口铁 c.高速合金钢 d.碳塑纤维 ' end def question2 puts '杨过、程英、陆无双铲除了情花,造成了[] a.使这种植物不再害人 b.使一种珍稀物种灭绝 c.破坏了那个生物圈的生态平衡 d.造成该地区沙漠化 ' end def question3 puts '蓝凤凰的致使华山师徒、桃谷六仙呕吐不止,如果你是大夫,会给他们开什么药[] a.阿司匹林 b.牛黄解毒片 c.氟酸 d.让他们喝大量的生牛奶 e.以上全不对' end end #学生甲的试卷类 class TestPaperA < TestPaper def question1 super puts '答案:b' end def question2 super puts '答案:a' end def question3 super puts '答案:c' end end #学生乙的试卷类 class TestPaperB < TestPaper def question1 super puts '答案:d' end def question2 super puts '答案:b' end def question3 super puts '答案:a' end end puts '学生甲抄的试卷' student1 = TestPaperA.new student1.question1 student1.question2 student1.question3 puts '学生乙抄的试卷' student2 = TestPaperB.new student2.question1 student2.question2 student2.question3

可以看出,抽取出来一个公共的试卷类,让甲乙去继承,公用其中的试题。这时再看TestPaperA和TestPaperB,不同的只有答案a、b、c、d不一样,其他的都一样。

# -*- encoding: utf-8 -*- class TestPaper def question1 puts '杨过得到,后来给了郭靖,炼成倚天剑,屠龙刀的玄铁可能是[] a.球墨铸铁 b.马口铁 c.高速合金钢 d.碳塑纤维 ' puts "答案:#{answer1}" end def question2 puts '杨过、程英、陆无双铲除了情花,造成了[] a.使这种植物不再害人 b.使一种珍稀物种灭绝 c.破坏了那个生物圈的生态平衡 d.造成该地区沙漠化 ' puts "答案:#{answer2}" end def question3 puts '蓝凤凰的致使华山师徒、桃谷六仙呕吐不止,如果你是大夫,会给他们开什么药[] a.阿司匹林 b.牛黄解毒片 c.氟酸 d.让他们喝大量的生牛奶 e.以上全不对' puts "答案:#{answer3}" end def answer1; end def answer2; end def answer3; end end #学生甲的试卷类 class TestPaperA < TestPaper def answer1 'b' end def answer2 'a' end def answer3 'c' end end #学生乙的试卷类 class TestPaperB < TestPaper def answer1 'd' end def answer2 'b' end def answer3 'a' end end puts '学生甲抄的试卷' student1 = TestPaperA.new student1.question1 student1.question2 student1.question3 puts '学生乙抄的试卷' student2 = TestPaperB.new student2.question1 student2.question2 student2.question3

这里将TestPaperA和TestPaperB中的答案抽离到了父类中,仅仅保存不同的部分。

父类成为子类的模板,所有重复的代码都应该上升到父类去,而不是让每个子类都去重复。

当我们要完成在某一细节层次一致的过程或一系列步骤,但其个别步骤在更详细层次上的实现可能不同时,我们通常考虑使用模板方法模式来处理。

【设计模式中的模板方法模式在Ruby中的应用实例两则】相关文章:

Ruby中使用设计模式中的简单工厂模式和工厂方法模式

详解Ruby中的循环语句的用法

Ruby设计模式编程之适配器模式实战攻略

Ruby程序中正则表达式的基本使用教程

ruby声明式语法的实现例子

Ruby中钩子方法的运用实例解析

Ruby中的反射(Reflection)应用实例

Ruby使用设计模式中的代理模式与装饰模式的代码实例

分析Cache 在 Ruby China 里面的应用情况

在Ruby on Rails中使用AJAX的教程

精品推荐
分类导航