Singleton Classes

What is Singleton? Singleton is a design pattern that exists to address a problem: say you have a class to represent an object; and only one of that object can exist at any time, no more. Like a database. Or a user’s screen. Or a graphic driver. Or, in single-player games, a player.

Technically, there’s nothing stopping you from creating two instances; just use ClassName.new!

Singleton addresses this problem with two prongs:

  1. It makes the constructor private, so you cannot instantiate the object normally; and
  2. It makes a public, static instance method, to get the one (and only) instance.

And this solves both problems easily!

Although it’s more common in object-oriented applications, it happens occasionally that you need a singleton class in your website. How do you do it?

The same way you do it for a Ruby program. You add the following to your class:


include Singleton

This makes your class a singleton class; the constructor becomes private, and it has a static function called instance to get the instance. Also, if you check two singleton instances with ==, they’re always equal. Check out the sample below:


class UniqueResource
include Singleton
...
end

d = UniqueResource.new #error
first = UniqueResource.instance # => UniqueResource.instance
second = UniqueResource.instance
first == second # => true
...

Simple! And that’s singleton, the Ruby on Rails way! For more in-depth details, you can check the Ruby Singleton API.

If you have a singleton class, it doesn’t make sense to make it a subclass of ActiveRecord; just use regular getters and setters and set all the values you need inside your class itself.

Forums Discussion: http://www.railsrocket.com/forums/topic.php?id=17

About Ashiq Alibhai

Ashiq Alibhai, PMP, has been a Rails aficionado since 2007, and developed web applications since early 2003, where he learned PHP in one summer. As the driving-force behind RailsRocket and the Launchpad project, he seeks to share the ease of development with Rails far and wide.
This entry was posted in Development and tagged , . Bookmark the permalink.

2 Responses to Singleton Classes

  1. anon says:

    thanks a lot dude

  2. Pingback: Websites tagged "singleton" on Postsaver