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.newin your object, and do whatever you want in there:You can also, obviously, use a different class method to obtain the object; make the
initializemethod 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
storeandlookupbits, and there isn’t anything better than aHashorArrayin 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: