Prevent duplicate objects in Ruby
This isn't exactly a singleton, but it's close, so I imagine it's common. I have a class (Foo) in which instances correspond to external data structures with unique IDs. I want to ensure that no two instances of Foo can have the same ID - if a constructor is called with the same id value, the original Foo instance with that ID, and all the other values are simply updated. In other words, something like:
class Foo
  def initialize(id, var1, var2)
    if Foo.already_has? id
      t = Foo.get_object(id)
      t.var1 = var1
      t.var2 = var2
      return t
    else
      @var1 = var1
      @var2 = var2
    end
end
I can think of two ways to do this:
I could keep an array of all instances of Foo as a class-level variable, then calling foo_instances.push(self) at the end of the initialization method. This strikes me as kind of ugly.
I believe Ruby already keeps track of instances of each class in some array - if so, is this accessible, and would it be any better than #1?
??? (Ruby seems to support some slick [meta-]programming tricks, so I wouldn't be surprised if there already is a tidy way of doing this that I'm missing.
 You can override Foo.new in your object, and do whatever you want in there:  
class Foo
  def self.new(id, var1, var2)
    return instance if instance = self.lookup
    instance = self.allocate
    instance.send :initialize, var1, var2
    return self.store(instance)
  end
end
 You can also, obviously, use a different class method to obtain the object;  make the initialize method private to help discourage accidental allocation.  
That way you only have one instance with every ID, which is generally much less painful than the pattern you propose.
 You still need to implement the store and lookup bits, and there isn't anything better than a Hash or Array in your class to do that with.  
You want to think about wrapping the things you store in your class in a WeakRef instance, but still returning the real object. That way the class can enforce uniqueness without also constraining that every single ID ever used remain in memory all the time.
That isn't appropriate to every version of your circumstances, but certainly to some. An example:
  # previous code omitted ...
  return store(instance)
end
def self.store(instance)
  @instances ||= {}
  @instances[instance.id] = WeakRef.new(instance)
  instance
end
def self.lookup(id)
  @instances ||= {}
  if weakref = @instances[id] and weakref.weakref_alive?
    return weakref.__getobj__  # the wrapped instance
  else
    return nil
  end
end
上一篇: 与Ruby访问器方法混淆
下一篇: 在Ruby中防止重复的对象
