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. :-)
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)
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



덧글