Ruby语言经典代码讲座:单态类(Singleton Class)

『》』什么是单态类?
『《』单态类是一种创建性模型类,它用来确保只产生一个实例,并提供一个访问它的全局切入点。

『》』在Ruby语言中,如何写第一个单态类代码?
『《』我们给出一个具体单态类DbConnect代码(线程安全):
require 'singleton'
class DbConnect
include Singleton
end
『》』如何调用我们上述的单态类DbConnect?
『《』我们通过irb来实际操作一下:

『》』在Ruby语言中,如何写第二个单态类代码?
『《』我们给出第二个具体单态类DbConnect代码(非线程安全):
DbConnect = Object.new
class << DbConnect
def foo ; end
def bar ; end
end
『》』如何调用我们第二个单态类DbConnect?
『《』我们还是通过irb来实际操作一下:

『》』在Ruby语言中,如何写第三个单态类代码?
『《』我们给出第三个具体单态类DbConnect代码(非线程安全):
module DbConnect
def eins;end
def zwei;end
module_function :eins,:zwei
end

等价代码为:
DbConnect = Module.new
class << DbConnect
def eins;end
def zwei;end
end
module DbConnect
private
def eins;end
def zwei;end
end

Comments

Popular posts from this blog

英语字母a的发音