Design patterns in Ruby serials -Singleton

What’s the Singleton?

Wikipedia said as below:

In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects. The term comes from the mathematical concept of a singleton.

That sounds cool,but if you wanna use it well,you must know what’s your problems?what does it do in the software engineer ,or you will abuse it in the project.

The singleton design pattern did these issues

  • How can it be ensured that a class has only one instance?
  • How can the sole instance of a class be accessed easily?
  • How can a class control its instantiation?
  • How can the number of instances of a class be restricted?

How singleton design pattern solve these issue?

  • Hide the constructor of the class.
  • Define a public static operation (getInstance()) that returns the sole instance of the class.

Why hide the constructor of class?

The hidden constructor (declared private) ensures that the class can never be instantiated from outside the class.

The public static operation can be accessed easily by using the class name and operation name (Singleton.getInstance()).

Common use scenes:

  • 1,Abstract factory,builder and prototype can use it in their implement.
  • 2,Facade objects are often singletons because only one facade object is required.
  • 3,State objects are often singletons.
  • 4,Singletons are often preferred to global variables because:
They do not pollute the global namespace (or, in languages with namespaces, their containing namespace) with unnecessary variables.[4]
They permit lazy allocation and initialization, whereas global variables in many languages will always consume resources.

Based on Rails framework ,there is a singleton class called logger.

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')

Ruby singleton module

require 'singleton'

class Logger
include Singleton

def initialize
@log = File.open("log.txt", "a")
end

def log(msg)
@log.puts(msg)
end
end

Logger.instance.log('message 2')
Like what you read? Give Marc StevenCoder a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.