Robert Klemme wrote:
> Sam Kong wrote:
> > Hi!
> >
> > Sometimes a class provides object instantiation methods other than new.
> > See an example.
> >
> > class Color
> >     def initialize r, g, b
> >         @r = r
> >         @g = g
> >         @b = b
> >     end
> >
> >     def to_s
> >         "R: #{@r}, G: #{@g}, B: #{@b}"
> >     end
> >
> >     class << self
> >         def red
> >             new 255, 0, 0
> >         end
> >
> >         def blue
> >             new 0, 0, 255
> >         end
> >
> >         def green
> >             new 0, 255, 0
> >         end
> >     end
> > end
> >
> > puts Color.new(100, 120, 140)
> > 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 the
> > 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 = 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   = new 0xFF, 0x00, 0x00
>    BLUE  = new 0x00, 0x00, 0xFF
>    GREEN = new 0x00, 0xFF, 0x00
> end

This looks tricky and wonderful.
I just tried to make a simple example which was not intended to be
ooptimal.
I will apply your way when I need to make a real code.:-)
Thank you.

Sam