Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Ruby > class design

Reply
Thread Tools

class design

 
 
Spitfire
Guest
Posts: n/a
 
      12-25-2006
How do I design a class such that it can never be instantiated? Say
for example a class containing static members alone, which requires no
instantiation!

--
_ _ _]{5pitph!r3}[_ _ _
__________________________________________________
“I'm smart enough to know that I'm dumb.”
- Richard P Feynman
 
Reply With Quote
 
 
 
 
Robert Klemme
Guest
Posts: n/a
 
      12-25-2006
On 25.12.2006 20:54, Spitfire wrote:
> How do I design a class such that it can never be instantiated? Say
> for example a class containing static members alone, which requires no
> instantiation!


You can apply some tactics to make it harder but AFAIK there is no safe
way to completely prevent instantiation. Typically something like this
will suffice

class Foo
def self.new(*a,&b) raise "Must not instantiate!" end
end

irb(main):004:0> Foo.new
RuntimeError: Must not instantiate!
from (irb):2:in `new'
from (irb):4
from :0

Other than that you can also use module Singleton, which is probably
better documentation wise:

irb(main):005:0> require 'singleton'
=> true
irb(main):006:0> class Bar
irb(main):007:1> include Singleton
irb(main):008:1> end
=> Bar
irb(main):009:0> Bar.new
NoMethodError: private method `new' called for Bar:Class
from (irb):9
from :0

Kind regards

robert
 
Reply With Quote
 
 
 
 
James Edward Gray II
Guest
Posts: n/a
 
      12-25-2006
On Dec 25, 2006, at 1:55 PM, Spitfire wrote:

> How do I design a class such that it can never be instantiated?
> Say for example a class containing static members alone, which
> requires no instantiation!


Just use a module for this:

module Static
# ... defined constants and methods here ...
end

James Edward Gray II

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
class design/ design pattern question Bartholomew Simpson C++ 2 06-12-2007 08:51 PM
class design vs. db design John_Woo Java 2 12-19-2006 08:27 PM
Nested Class, Member Class, Inner Class, Local Class, Anonymous Class E11 Java 1 10-12-2005 03:34 PM
A parameterized class (i.e. template class / class template) is not a class? christopher diggins C++ 16 05-04-2005 12:26 AM
Class design/design pattern resources TomTom MCSD 2 10-09-2004 07:38 AM



Advertisments
 



1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57