Ben Giddings <ben / thingmagic.com> wrote:
> Although Ruby allows the use of global variables, I still prefer not to 
> use them.  I am wary that someone else might have chosen the same 
> variable name as me, and besides, they just don't feel properly OO.  
> Singletons seem like the best solution to this problem, but I'm 
> concerned about garbage collection.
> 
> Say I have two classes that each do a lot of work.  I instantiate one, 
> do a bunch of calculations and return a result.  I then instantiate a 
> second class and do a bunch more work on that result.  Say both classes 
> want to use this global / singleton, and want to make sure that it 
> doesn't get garbage collected between calls, what's the best way to do 
> this?

Classes are global and a singleton instance will be referenced by a
static variable/class variable of the singleton class. (See the design
patterns book by the GOF.) I can't see a problem for the GC there.
It's easy to test: Invoke the GC within your example. Does it still
work?

I recommend that you try to avoid using global access paths to
singletons whenever you design a big application. The application will
be easier to maintain if you identify components and make each
component access global objects via access paths local to that
component. You could use another singleton to do so , e. g.
MyComponentGlobals.instance.getStats.

You can find some discussions about the problems singletons might
introduce here:
- Search for the thread "Q: Singleton" in comp.lang.smalltalk
- Read http://c2.com/cgi/wiki?SingletonPattern (and follow some of the
links)

Cheers
Sascha