Design Patterns in Ruby [Digest 10] Singleton
1440 ワード
Singleton is common for every coder. It provide only instance of class.
In ruby we can use Singleton Module, it is lazy instantiation
And we can use to implement eager instantiation
There are some other way to implement the singleton pattern:
or
The deficiencies are as below:
First, if you use a global variable or a constant for this purpose, there is no way to delay the creation of the singleton object until you need it. The global variable or constant is there from the moment we first set it.
Second, neither of these techniques does anything to prevent someone from creating a second or third instance of your supposedly singleton class.
class SimpleLogger
# Lots of code deleted...
@@instance = SimpleLogger.new
def self.instance
return @@instance
end
private_class_method :new
end
In ruby we can use Singleton Module, it is lazy instantiation
require 'singleton'
class SimpleLogger
include Singleton
# Lots of code deleted...
end
And we can use to implement eager instantiation
class SimpleLogger
# Lots of code deleted...
@@instance = SimpleLogger.new
# Lots of code deleted...
end
There are some other way to implement the singleton pattern:
$logger = SimpleLogger.new
or
Logger = SimpleLogger.new
The deficiencies are as below:
First, if you use a global variable or a constant for this purpose, there is no way to delay the creation of the singleton object until you need it. The global variable or constant is there from the moment we first set it.
Second, neither of these techniques does anything to prevent someone from creating a second or third instance of your supposedly singleton class.