From: "R. Mark Volkmann" Date: 2005-06-20T23:18:55+09:00 Subject: Re: preventing instantiation Quoting Steven Jenkins : > >>On 6/19/05, R. Mark Volkmann wrote: > >> > >>>What is the recommended way in Ruby to prevent other classes from creating > >>>instances of a given class? The class isn't a singleton. It creates > >>>several > >>>instances of itself and no additional instances should be able to be > >>>created. > > > > When I put the following in my class, it seems that even that class can't > > create instances. > > > > private_class_method :new > > > > I'm confused. How can I create a few objects within the class and then > > prevent other classes from creating additional instances? > > Does this do it? > > sjenkins@tidal ~ $ cat t.rb > require 'singleton' > > class A; end > > a0 = A.new > a1 = A.new > a2 = A.new > > class A > include Singleton > end > > a3 = A.new > sjenkins@tidal ~ $ ruby t.rb > t.rb:13: private method `new' called for A:Class (NoMethodError) > > Remember, 'include' is exectuable. That does work, but I see two issues with that approach. 1) it adds an "instance" method that isn't useful and is misleading 2) someone might think the class is a singleton when in fact it isn't -- R. Mark Volkmann Partner, Object Computing, Inc.