From: Marko Schulz Date: 2001-04-24T02:26:13+09:00 Subject: [ruby-talk:14093] Re: OO On Tue, Apr 24, 2001 at 12:55:52AM +0900, James Ponder wrote: > > I've been discussing this with some Java people, and they think I should > be using a "singleton" - although this word appears to be used in Ruby as > a way of adding methods to objects I've not seen it used in the same way > that Java people use it. Apparently in Java you do this by creating > a private constructor (so that nobody can instantiate the class) and have a > class variable that holds one instance of the object. The object is normally > instantiated in the class init code or in a "unless(obj) obj = MyClass.new()" > way within each class method. Just say require 'singleton' at the beginning of the file and include Singleton at the beginning of the class. Voila! You got a singleton according to the design pattern. Now you can't call 'new' on the class anymore, but have to use the method instance(). This is also described at the end of http://www.rubycentral.com/book/lib_patterns.html Note that some people think that singletons are evil since they are global variables in disguise: http://c2.com/cgi-bin/wiki?SingletonsAreEvil > In Ruby, can you stop someone being able to instantiate an object? Yes, use Module.private_class_method on new. -- marko schulz Dieser Satz beinhalten drei Fehller.