Ruby 標準庫 Singleton

Juanito FatasThinking about what to do.

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