From: Florian Gross Date: 2005-01-22T00:35:59+09:00 Subject: Re: Refernce objects Richard Turner wrote: > Hi, Moin. > I'm new to Ruby, so I'm still learning the Ruby Way. I'm also reading > Martin Fowler's 'Refactoring' at the moment and have realised that some > of the classes I've created in a program I'm writing fit his description > of value objects that should be refactored into reference objects. > Those classes are, in fact, wrappers over entities in a DB so I need a > factory (creation) method to always return the same object when given > the same creation parameter. E.g.: > > Section.getSection(10) always returns the same object representing the > record in the DB with primary key '10'. I think this is also called the Multiton pattern. Something like this ought to work: (I'm reusing .new here, I think it would be a bigger surprise to have .new raise an Exception than it not returning an unique object every time. You can however still provide your own constructor and make it private fairly easily with class << self; private :new; end) require 'thread' class MyMultiton # I'm not sure if this Mutex is really needed. The Hash class might # already be using a critical section around allocator block calls # anyway. Feedback on this is welcome. @instance_cache_mutex = Mutex.new @instance_cache = Hash.new do |hash, args| result = self.allocate result.send(:initialize, *args) hash[args] = result end def self.new(*args) @instance_cache_mutex.synchronize do @instance_cache[args] end end # Or whatever your initialize looks like... def initialize(value) @value = value end end It can probably be done in a simpler way, but this ought to work.