Use Ruby Proc class for factory pattern English Posting

I think Proc is good for factory pattern. Of course, if the concrete product needs subclassing or anything else that real class is needed, we have to code class for concrete product. However, if it is used for only simple work, Proc class is not bad choice. :-)
require 'singleton'

class RandFactory
  include Singleton
  def RandFactory.get_rand(mode = nil)
    ra = nil
    if mode == :FAKE
      ra = Proc.new { 1938 }
    else
      ra = Proc.new { rand(20) + 1930 }
    end
    
    ra.instance_eval do
      def year
        self.call
      end
    end
    
    ra
  end
end

r = RandFactory.get_rand
5.times { puts r.year }

puts '---------------------------------------'

r = RandFactory.get_rand(:FAKE)
5.times { puts r.year }

To tell the truth, we also can use Object, OpenStruct and so on for the purpose like below. :-)

require 'singleton'

class RandFactory
  include Singleton
  def RandFactory.get_rand(mode = nil)
    rander = Object.new
    if mode == :FAKE
      rander.instance_eval do
        def year; 1938; end
      end
    else
      rander.instance_eval do
        def year; rand(20) + 1930; end
      end
    end
    rander
  end
end


트랙백

이 글과 관련된 글 쓰기 (트랙백 보내기)
TrackbackURL : http://classpath.egloos.com/tb/4598214 [도움말]

덧글

덧글 입력 영역


구글애드센스