Design Patterns - Singleton

by Caleb Tennis

Over at the CodeSnipers site, Rusty Divine is running a multi part series on design patterns. He recently posted a look at the Singleton design pattern, with some Java and C# based examples.

I wanted to show that same pattern using Ruby:

require 'singleton'
class Hermit
include Singleton

That's it.

Using Ruby's powerful Mixin functionality, we bring the singleton code into our class definition. This automatically makes our class's new method private, and give us an instance method we can use to get our object:

irb(main):005:0> a =
NoMethodError: private method `new' called for Hermit:Class
from (irb):5
irb(main):006:0> a = Hermit.instance
=> #<Hermit:0x20a1cc>

That was easy, wasn't it?


2006-01-10 20:03:14
We should really consider building a catalog website translating most of the patterns. I've thought a lot about it and I think it could be a sensational community resource. I would be more than willing to help or maybe even spearhead a project like this, just as soon as I finish editing this book... :)

James Edward Gray II

2006-01-10 22:08:59
I haven't read through all of them, but this looks pretty good.
Nola Stowe
2006-01-11 06:53:50
Awesome! Thats really cool. :)
2006-01-11 09:31:54
Wow, I had no idea such a great resource already existed. Thanks for the link!

James Edward Gray II

Brian Miller
2006-01-20 14:22:12
Very stylish.

Just like the rest of Ruby.