in reply to Singletons and Inheritance

Looks ok to me. But I wouldn't make it completely impossible to create more than one instance (as you are doing here). I'd probably leave the new() method as a normal constructor and add a getInstance() method that implements the singleton.

Also, are you sure you want $object->new() to be meaningful? There have been discussions on it for ages, because there is no universally accepted behaviour (should it make a clone, or only copy the object reference, or create a new "empty" object...).

Replies are listed 'Best First'.
Re^2: Singletons and Inheritance
by PerlingTheUK (Hermit) on Jul 20, 2004 at 11:21 UTC
    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?
      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).