ruby中的单例模式

Singleton 模块实现了单态模式 (Singleton pattern)

 

一、用法 :

class Klass

include Singleton

# ...

end

1 、这确保只有一个 Klass 的实例得到调用。 “这个实例”可以它创建的。

a,b = Klass.instance, Klass.instance a == b # => true a.new # NoMethodError - new 现在是 private …

2 、在实例化时创建“这个实例”,换句话说,第一次是对 Klass.instance() 的调用 , 从而

class OtherKlass

include Singleton

# ...

end

ObjectSpace.each_object(OtherKlass){} # => 0.

3 、这种行为受到继承和克隆的保护。

二、这是通过做标记来完成

1 Klass.new Klass.allocate – 被看成是 private

2 Klass.inherited(sub_klass) Klass.clone() – 用于确保单态模式可被适当地继承和克隆。

3 Klass.instance() – 返回“这个实例”。这个方法体很简单:

def Klass.instance()

return @__instance__

end

4 Klass._load(str) – 调用 Klass.instance()

5 Klass._instantiate?() – 返回“这个实例”或 nil 。这个钩子方法在一个等待循环内放置一个调用 Klass.instance() 的第二 ( 或第 n) 线程。 The return value signifies the successful completion or premature termination of the first, or more generally, current "instantiation thread".

三、 Singlton 的实例方法是:

1 clone dup – 引发 TypeErrors 异常来防止克隆和转储。

2 _dump(depth)— 返回空字符串。 Marshalling strips by default all state information, e.g. instance variables and taint state, from ``the instance’’. Providing custom _load(str) and _dump(depth) hooks allows the (partially) resurrections of a previous state of ``the instance’’.

 

Ruby 的 singleton 很容易!


require 'singleton'

class King
  include Singleton
end

k = King.new      #Error
k = King.instance #Use it to get King instance


你可能感兴趣的:(thread,Ruby)