This post is part of a series of reviews on the book Design Patterns in Ruby. Check out the Introduction post for a full table of contents along with some generic principles regarding Design Patterns.
An object of which is permitted only a single instance with global access is a Singleton, simple as that. If you must have only one instance of a class and be able to access that instance from anywhere, then you’re applying the Singleton pattern.
Since anything that must be unique is a Singleton, let’s use myself is an example. I sure don’t want other instances of Me walking around.
class Pedro @@instance = Pedro.new def age puts Time.now.year - 1990 #poor age calculation ftw end def self.instance @@instance end private_class_method :new end begin #this won't work p = Pedro.new p.age rescue #but this will Pedro.instance.age end
The code is simple, we’re using a class variable to hold an instance of Pedro and turning the method new private, so there’s no way to create other instances of Pedro, you have to call Pedro.instance to get its instance and work from that.
To make things simpler, Ruby ships with a Singleton module so you don’t have to write any code regarding the Singleton pattern, so let’s refactor our previous code to use that instead:
require 'singleton' class Pedro include Singleton def age puts Time.now.year - 1990 #poor age calculation ftw end end begin #this won't work p = Pedro.new p.age rescue #but this will Pedro.instance.age end