本文簡要介紹ruby語言中 Singleton模塊
的用法。
用法
要使用 Singleton
,請將模塊包含在您的類中。
class Klass
include Singleton
# ...
end
這確保了隻能創建一個 Klass 實例。
a,b = Klass.instance, Klass.instance
a == b
# => true
Klass.new
# => NoMethodError - new is private ...
該實例是在第一次調用 Klass.instance() 時創建的。
class OtherKlass
include Singleton
# ...
end
ObjectSpace.each_object(OtherKlass){}
# => 0
OtherKlass.instance
ObjectSpace.each_object(OtherKlass){}
# => 1
此行為在繼承和克隆下保留。
執行
以上是通過以下方式實現的:
-
將 Klass.new 和 Klass.allocate 設為私有。
-
覆蓋 Klass.inherited(sub_klass) 和 Klass.clone() 以確保在繼承和克隆時保留
Singleton
屬性。 -
提供每次調用時返回相同對象的 Klass.instance() 方法。
-
覆蓋 Klass._load(str) 以調用 Klass.instance()。
-
覆蓋 Klass#clone 和 Klass#dup 以引發 TypeErrors 以防止克隆或複製。
Singleton
和 Marshal
默認情況下,Singleton 的 #_dump(depth) 返回空字符串。默認情況下編組將刪除狀態信息,例如來自實例的實例變量。使用 Singleton
的類可以提供自定義 _load(str) 和 _dump(depth) 方法來保留實例的某些先前狀態。
require 'singleton'
class Example
include Singleton
attr_accessor :keep, :strip
def _dump(depth)
# this strips the @strip information from the instance
Marshal.dump(@keep, depth)
end
def self._load(str)
instance.keep = Marshal.load(str)
instance
end
end
a = Example.instance
a.keep = "keep this"
a.strip = "get rid of this"
stored_state = Marshal.dump(a)
a.keep = nil
a.strip = nil
b = Marshal.load(stored_state)
p a == b # => true
p a.keep # => "keep this"
p a.strip # => nil
相關用法
- Ruby SingleForwardable模塊用法及代碼示例
- Ruby SingleLine.new用法及代碼示例
- Ruby SingleForwardable.def_single_delegators用法及代碼示例
- Ruby SizedQueue clear()用法及代碼示例
- Ruby SizedQueue push()用法及代碼示例
- Ruby SimpleDelegator.__setobj__用法及代碼示例
- Ruby SizedQueue shift()用法及代碼示例
- Ruby Signal.trap用法及代碼示例
- Ruby SizedQueue enq()用法及代碼示例
- Ruby SizedQueue max()用法及代碼示例
- Ruby SizedQueue empty?用法及代碼示例
- Ruby SimpleDelegator類用法及代碼示例
- Ruby SizedQueue pop()用法及代碼示例
- Ruby SizedQueue new()用法及代碼示例
- Ruby SizedQueue length()用法及代碼示例
- Ruby SignalException類用法及代碼示例
- Ruby SizedQueue deq()用法及代碼示例
- Ruby Signal.list用法及代碼示例
- Ruby SizedQueue close()用法及代碼示例
- Ruby Signal模塊用法及代碼示例
- Ruby Signal.signame用法及代碼示例
- Ruby SizedQueue size()用法及代碼示例
- Ruby SizedQueue max=用法及代碼示例
- Ruby Symbol capitalize用法及代碼示例
- Ruby Spotter.spot_op_asgn2_for_name用法及代碼示例
注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 Singleton模塊。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。