Tuesday, October 10, 2006

Singleton classes not seemingly the same as Singleton pattern

So I was looking at someone else's code today, and I saw this:

module Formats
class BasicNestedFormat
class << self
def foo
...foo code...
end
end
end
end


Huh? What did "<< self" mean? I guess I didn't read my Ruby book closely enough. It's apparently a "singleton class", which doesn't seem to be exactly a "singleton pattern".

A "singleton class" is a sole metaclass that 'holds' methods for a single object. It would have been called a 'metaclass', except that it's not the class of a class, but a class of a class that only exists for that one object.

Keep in mind that this is the case because you can add methods to objects in ruby at runtime. Since everything in Ruby is an object(even the classes), it has to go somewhere, and in an anonymous metaclass is where it goes.

One can almost think of them as 'static' methods in Java. However, because objects can be added methods at runtime, they don't necessarily belong in the class, but to the metaclass of an object that only belongs to that object.

They're not like 'static' classes of Smalltalk or Java. You can call self (like this in Java) in Ruby's 'static' methods.

It's a curious construct because you can use it to specify 'static' methods all in one go. It's the equivalent of the following:

module Formats
class BasicNestedFormat
def self.foo
...foo code...
end
end
end


Apparently, you can also use it to do prototype factories. There's more to it than meets the eye. You can find better explainations here and here.

Ruby is weird.


Wilhem has built Annologger, a tool that lets people worship your dentist appointments.

No comments:

Post a Comment