Singleton made simple in Ruby

Tags:

하하. 이런게 될줄이야;;

irb(main):001:0> require “singleton”
=> true
irb(main):002:0> class Foo
irb(main):003:1> include Singleton
irb(main):004:1> end
=> Foo
irb(main):005:0> f = Foo.new
NoMethodError: private method `new’ called for Foo:Class
from (irb):5
from :0
irb(main):006:0> f = Foo.instance
=> #
irb(main):007:0> f2 = Foo.instance
=> #
irb(main):008:0> f == f2
=> true
irb(main):009:0> f.object_id == f2.object_id
=> true

이 코드가 SMP 등에서도 안전한지는 더 알아봐야할 듯하네요..

물론 C++에도 비슷한 녀석이 있죠.. Modern C++ Design 에서도 그러한 Singleton에 대해서 언급하고 있습니다. (애석하게도 MC++에서 나오는 Double Checked Locking Pattern에 대한 설명은 잘못되었지만) 하지만 그건 어디까지나 core 라이브러리는 아닌고로.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *