Ruby new方法的理解。

之所以喜欢ruby,是因为理解ruby后,用ruby解释所有东西都那么自然。比如别的语言创建对象都是Xxx instance = new Xxx(),不要问为什么,就是要这么写。当然Ruby创建对象是instance = Xxx.new,但是这里,我们可以用ruby的commonsense来解释。

Xxx.new可以看成Xxx执行了一个类方法:new,运行以下代码便知。
class Test

	def self.new *args, &blk
		puts *args.join(',')
	end

	def initialize a, b, c
		puts "Kan Bu Jian Wo!!"
	end

end

Test.new(1, 2, 3) # 1,2,3



由上可知,ruby创建实例实际是调用了类的方法new,所以我们重写了new方法所以就创建不出实例了。

最后献上根据以上解释写出的单例模式:
module Singleton
	
	def self.included(klass)
		klass.class_eval do
			(class << self; self; end).class_eval do
				alias_method :original_new, :new
				def new *args, &blk
					@instance ||= original_new(*args, &blk)
				end
			end
		end
	end
	
end

class Test
	include Singleton
end

tst1 = Test.new
tst2 = Test.new

puts tst1.object_id
puts tst2.object_id


include Singleton模块的所有类通过new产生的实例都是同一个实例。

你可能感兴趣的:(Ruby)