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

Tags: ,     Posted in Development

Rate this article:
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Further Reading

Leave a Reply