CSC/ECE 517 Fall 2011/ch4 4h sv
Design Patterns in Ruby
Singleton Pattern
The Singleton design pattern is used to restrict the instantiation of a class to only one instance which is globally available. This is used in situations where a user needs an instance of the class to be available in various parts of the application, being available for logging functionality, communictaion with external systems and database access etc. The Singleton pattern is available as a mixin in the Ruby library. Including it in the code makes the new method private and provides an instance method used to create or access the single instance.
Below is an illustration of the implementation of Singleton Design Pattern in Ruby:
class Logger def initialize @log = File.open("log.txt", "a") end @@instance = Logger.new def self.instance return @@instance end def log(msg) @log.puts(msg) end private_class_method :new end Logger.instance.log('message 1')
In this code example, inside class Logger we create instance of the very same class Logger and we can access that instance with class method Logger.instance whenever we need to write something to the log file using the instance method "log". In the initialize method we just opened a log file for appending, and at the end of Logger class, we made method "new" private so that we cannot create new instances of class Logger. And, that is Singleton Pattern: only one instance, globally available.
require 'singleton' class Example include Singleton attr_accessor :val end r = Registry.new #throws a NoMethodError r = Registry.instance r.val = 5 s = Registry.instance puts s.val >> s.val = 6 puts r.val >> s.dup >>