class design

S

Spitfire

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!
 
R

Robert Klemme

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
 
J

James Edward Gray II

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,221
Messages
2,571,134
Members
47,748
Latest member
LyleMondra

Latest Threads

Top