A lot of articles you’ll find on the Singleton pattern starts off by telling you how it’s the worst and most hated of all the design patterns. However, most people also comment about how we can’t seem to get by without the singleton. In Ruby there are examples of singletons in Webrick, Rails and even rake. I’m even tempted to fire up a singleton to help keep track of my in-memory datastore, but I’m going to sleep on it for a night to make sure it’s not a case of finding out about a hammer and seeing lots of nails…

So, what is a singleton and why is it so bad? “One Object, Global Access” These four words are from Olsen’s Design Patterns in Ruby and answer both questions for us.

When you create a singleton class you’re creating a class that can have only one instance of itself and provides global access to that single instance. Creating your own singleton in Ruby isn’t too difficult and there’s a great example here. The class your creating a singleton of has a class variable that’s the instance of itself and then the class controls the access to that instance. You also place the “new” method inside the private methods so that nothing else can create an instance of it.

class Example
    @@instance = Example.new

    #...other methods...

    def self.instance
        return @@instance
    end

    private_class_method :new
end 

Seeing as how we can’t get away from singletons Ruby even goes through the trouble of providing the Singleton module to aid in the setup.

And the bad part? Global access. A singleton provides a way for all of your classes to communicate together, and it seems like it might be easy to get carried away with or lose track of what’s taking to what. My primary hesitation in using it for my in-memory datastore is exposing it to too many things. I’ve already switched up my implementation from what I posted on Tuesday though, so this weekend I’ll do a follow up on what I decide to do.