On 3/22/06, Sam Kong <sam.s.kong / gmail.com> 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?
>

That's the "Factory Method" pattern.  It's handy when you want
SomeClass.new to return an instance of SomeOtherClass, or just when
you want things to be easier to read.

One of my favorite examples (I think this is a Martin Fowler trick) is:
some_date = december(10,2006)