in reply to Re: Singletons and Inheritance
in thread Singletons and Inheritance

I surely have to take the copy part out as it is useless, for singleton objects anyway, but I want to accept arguments even though the constructor will just ignore use them if a reference to an old object is returned.
Maybe I should warn the user if he does so.
I am not sure how new and get instance would work together though, which instance would I return if I have two objects. What is the benefit of this?

Replies are listed 'Best First'.
Re^3: Singletons and Inheritance
by Joost (Canon) on Jul 20, 2004 at 11:28 UTC
    It's just my personal preference - I've run into too many situations where in the end you do NOT want a forced singleton. So I'd do:

    my %instances; sub getInstance { my $class = shift; $instances{$class} ||= $class->new(@_); return $instances{$class}; }
    And if any code calls $class->new() directly, they'll get another instance which getInstance knows nothing about, so it doesn't interfere.

    Also, I think splitting up the code like this makes it a lot clearer.

    OTOH, if you have a good reason to always disallow more than one instance (I can only think of interfaces to hardware), you could rename it so that getInstance is named new() and new() is named _new() or something (and don't document _new() in the public API).