ruby设计模式

模板模式意味着先做一个很抽象的模板,搭一个骨架, 然后就可以让拿到模板的往里面添加东西。


给一个具体的列子吧


比如说 报告, 你到网上收下 报告的模板很多吧。 但是很多都是大同小异吧。


现在老板让你写两份报告,一份是HTML版的,一份是纯文本的。


让我们一起来建立三个class


1. Report 


2. HTMLReport


3. PlaneTextReport


class Report
  def initialize
    @title = "html report title"
    @text = ["report line 1", "report line 2", "report line 3"]
  end

  def output_report
    output_start
    output_body
    output_end
  end

  
  def output_start
  end

  def output_body
    @text.each do |line|
      output_line(line)
    end
  end

  def output_line(line)
    raise 'Called abstract method !!'
  end

  def output_end
  end
end


好了,最基本的模板弄好了


现在就可以开始弄html 的模板


class HTMLReport < Report

  def output_start
    puts "<html><head><title>#{@title}</title></head><body>"
  end


  def output_line(line)
    puts "<p>#{line}</p>"
  end

  
  def output_end
    puts '</body></html>'
  end
end


最后就是纯文本模板了


class PlaneTextReport < Report
  #
  def output_start
    puts "**** #{@title} ****"
  end

  
  def output_line(line)
    puts line
  end
end




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值