singleton in ruby
What is Singleton?
singleton is a way to “ensure a class only has one instance, and provide a global point of access to it”
WIKI: singleton pattern
the singleton pattern is a software design pattern that restricts the instantiation of a class to one object
You can achieve the singleton using class initialization private or using singleton module.
Singleton module gives a broader implementation by achieving the following things:
- Making Klass.new and Klass.allocate private.
- Overriding Klass.inherited(sub_klass) and Klass.clone() to ensure that the Singleton properties are kept when inherited and cloned.
- Providing the Klass.instance() method that returns the same object each time it is called.
- Overriding Klass._load(str) to call Klass.instance().
- Overriding Klass#clone and Klass#dup to raise TypeErrors to prevent cloning or duping.
Here a simple code snippet to make a singleton class, but you can always use singleton module](https://www.rubydoc.info/stdlib/singleton/Singleton)
# minimal example for singleton pattern
class Configs
class << self
def instance
@instance ||= new
end
private :new
end
end
# using singleton module
require 'singleton'
class Config
include Singleton
end