Ruby 官方函式庫有 Singleton
這個 Module。
require 'singleton'
class TheOneAndOnly
include Singleton
end
用 instance
來獲得獨一無二的物件:
> TheOneAndOnly.instance
=> #<TheOneAndOnly:0x007f9a5c7b1bc0>
> TheOneAndOnly.instance
=> #<TheOneAndOnly:0x007f9a5c7b1bc0>
> TheOneAndOnly.new
NoMethodError: private method `new' called for TheOneAndOnly:Class