Thursday, December 28, 2006

Design Patterns in Ruby : Singleton

Singleton pattern in Ruby just simple. Only thing is you need to include singleton module. Lets look at sample ruby program.

require 'singleton'
class MyClass
include Singleton
end

sing 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 = MyClass.new
NoMethodError: private method `new' called for MyClass:Class
from (irb):5
irb(main):006:0> a = MyClass.instance
=> #

No comments: