Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Singleton class - instance or class variables?

0 views
Skip to first unread message

Caleb Tennis

unread,
Dec 19, 2005, 8:13:15 PM12/19/05
to
When using a singleton class (one that includes Singleton, not an
eigenclass), can anyone think of any advantage/disadvantage to using
class variables over instance variables (or visa versa) to access
data in the class?

Thanks,
Caleb


Eero Saynatkari

unread,
Dec 19, 2005, 9:03:49 PM12/19/05
to

I would recommend using class instance variables,
but the only reason I can think relates to resource
control and instance instantiation. For the typical
case one could just as well use classes and class
instance methods.

> Thanks,
> Caleb


E

--
Posted via http://www.ruby-forum.com/.


Joel VanderWerf

unread,
Dec 19, 2005, 9:19:57 PM12/19/05
to

In answer to this question and the one about thread-specific singletons:
another approach to consider is using a dependency injection framework.
They all support singleton services, and at least some of them support
services that return one unique object per thread.

One disadvantage to using class variables (@@var) is that they are (in
the current ruby) per-hierarchy, not per class. So a subclass will share
the value of @@var. This is, I've heard, going to change in ruby 2.0.

--
vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407


ara.t....@noaa.gov

unread,
Dec 19, 2005, 9:49:56 PM12/19/05
to

inheritence will break with either.

with @@var then

class Singleton
@@var = 42
end

class SingletonII < Singleton
@@var = 'forty-two'
end

class Singleton
p @@var #=> 'forty-two'
end

but with @var

class Singleton
@var = 42
end

class SingletonII < Singleton
end

class SingletonII
p @var #=> nil
end

my traits lib solves this - if inheritence of class data is important. it may
not be.

regards.

-a
--
===============================================================================
| ara [dot] t [dot] howard [at] noaa [dot] gov
| all happiness comes from the desire for others to be happy. all misery
| comes from the desire for oneself to be happy.
| -- bodhicaryavatara
===============================================================================

0 new messages