Last active
December 17, 2015 00:59
-
-
Save xpepper/5524811 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# A hand-rolled singleton behaviour | |
# | |
class SnowFlake | |
class << self | |
private :new | |
end | |
def self.instance | |
@instance ||= new | |
end | |
end | |
p SnowFlake.instance # => #<SnowFlake:0x1003adfd8> | |
p SnowFlake.instance # => #<SnowFlake:0x1003adfd8> | |
p SnowFlake.new | |
# => NoMethodError: private method ‘new’ called for SnowFlake:Class | |
# | |
# Singleton module from Ruby's standard lib | |
# | |
require 'singleton' | |
class SnowFlake | |
include Singleton | |
end | |
p SnowFlake.instance # => #<SnowFlake:0x1003adff8> | |
p SnowFlake.instance # => #<SnowFlake:0x1003adff8> | |
p SnowFlake.new | |
# => NoMethodError: private method ‘new’ called for SnowFlake:Class |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment