Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a Class using the Singleton Design Pattern in Ruby?

The singleton pattern is a design pattern that is used to restrict instantiation of a class to one object instance. Although I know how to code the singleton pattern in C++ and Java, I was wondering if anyone know how to implement it in Ruby?

like image 893
CodingWithoutComments Avatar asked Aug 07 '08 13:08

CodingWithoutComments


2 Answers

Actually, the above answer was not completely correct.

require 'singleton'

class Example
  include Singleton
end

You also need to include the require 'singleton' statement.

like image 161
CodingWithoutComments Avatar answered Nov 13 '22 05:11

CodingWithoutComments


Use the singleton module:

class Clazz
  include Singleton
end

See http://www.ruby-doc.org/stdlib/libdoc/singleton/rdoc/index.html for more info.

like image 34
cynicalman Avatar answered Nov 13 '22 05:11

cynicalman