`
jlaky
  • 浏览: 42886 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Design Patterns in Ruby [Digest 10] Singleton

阅读更多

Singleton is common for every coder. It provide only instance of 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.

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics