From: Robert Dober Date: 2006-03-23T18:29:19+09:00 Subject: Re: Is this a kind of design patterns? ------=_Part_1914_14013178.1143106142635 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable Content-Disposition: inline let us wrap const_get begin const_get(...) rescue NameError super(...) end in order to get NoMethodError instead of a NameError Cheers Robert On 3/23/06, Robert Klemme wrote: > > Jim Weirich wrote: > > Robert Klemme wrote: > >> Sam Kong wrote: > >>> end > >>> def blue > >>> puts Color.red > >>> puts Color.blue > >>> > >>> > >>> Is this one of design patterns, or just a simple idiom? > >>> It's similar to a factory method pattern but it's not according to th= e > >>> definition. > >>> Is there any name for it? > >> Since you invoke a class's method "new" like any other method of any > >> other object (no special syntax) you can say with some justification > >> that all classes are basically factories. > >> > >> IMHO your example is not optimal because it wastes resources. Since > >> Color is immutable anyway constants seem a better choice: > >> > >> Color =3D Struct.new :r, :g, :b > >> class Color > >> def to_s > >> sprintf "R: 0x%02x, G: 0x%02x, B: 0x%02x", self.r, self.g, self.b > >> end > >> > >> RED =3D new 0xFF, 0x00, 0x00 > >> BLUE =3D new 0x00, 0x00, 0xFF > >> GREEN =3D new 0x00, 0xFF, 0x00 > >> end > > > > I was thinking along the same lines, but I do like the method interface > > (e.g. Color.red over Color::RED). My suggestion would have been > > something like: > > > > class Color > > ... > > class << self > > def red > > @red ||=3D new 255, 0, 0 > > end > > ... > > end > > end > > IMHO this is not thread safe. If you need the method interface, you > could do something like > > class Color > def self.method_missing(s,*a,&b) > if a.empty? && b.nil? > const_get s.to_s.upcase > else > super > end > end > end > > :-) > > robert > > > -- Deux choses sont infinies : l'univers et la b=EAtise humaine ; en ce qui concerne l'univers, je n'en ai pas acquis la certitude absolue. - Albert Einstein ------=_Part_1914_14013178.1143106142635--