From: Florian Gross Date: 2004-11-18T01:53:16+09:00 Subject: Re: Kernel#singleton_class trans. (T. Onoma) wrote: > On Tuesday 16 November 2004 09:18 am, Florian Gross wrote: > | Why don't use globals (or a constant) or a Module with module functions > | instead? I don't understand how singletons are useful for pools however. > | Could you explain? > > Well, with globals I can't control namespace. And modules have there one > issues --like what if I change my mind? And not being able to subclass. It depends: $colors::red # => "red" $colors::blue # => "blue" $colors::green # => "two colors ought to be enough for everyone" where: $colors = Module.new do; extend self define_method("red") { "red" } define_method("blue") { "blue" } define_method("green"){"two colors ought to be enough for everyone"} end I'm pretty sure I could also come up with a syntax that makes it feel more natural. > As for a constant, in a way that basically what one's doing. But the singleton > also prevents any other instance of that kind. Granted in many cases that > probably doesn't really matter. So sure I could probably just use a constant > and not worry about the potential abuses. Of course I could also never bother > to make a method private too. Maybe that's overstating it a bit, but the > point is, there are always multiple ways of doing things. Singleton Pattern > is just another tool, and if the shoe fits then where it. I don;t think we > should throw it out just b/c it's easy to abuse. I guess your problem is that you are creating a class at all. Why don't just assign a single Object to a constant and add methods to that single object directly? (The def obj.method() end syntax makes this quite convenient.) I'm still interested in how to do resource pools using Singletons. > How about InfinityClass. Singletons can be immutable too. I think they should only be allowed to be immutable or else they lead to very tight coupling. But I still wonder why you need a class when all you want is a single Object anyway. > | isn't "singleton class" > | the term that is most commonly used already? > Not substantially so. We've seen cases of the term virtual class. And I've > seen the term metaclass at least as often --especially in libs. Still, I feel like "singleton class" is used more than the others. Maybe you could grep #ruby-talk logs and compare the usage of the terms? (But be sure to filter out the few occurrences of SingleInstanceClasses that currently share the same name or the statistic will be slightly biased.) > The monotheistic doctrine of an OOP developer: God is Singleton. Most gods want you to believe that so that they can get power exclusively. Having just one god will make it difficult to replace it by a mock god when testing your believes.