Design Patterns - A Singleton in Ruby
Submitted by Caleb Tennis on Wed, 2006-01-11 10:48.
Rusty Divine 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 end
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 = Hermit.new
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?
- Caleb Tennis's blog
- Login to post comments









Recent comments
7 years 20 weeks ago
7 years 40 weeks ago
7 years 41 weeks ago