Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re^2: Singletons and Inheritance

by PerlingTheUK (Hermit)
on Jul 20, 2004 at 11:21 UTC ( [id://375872]=note: print w/replies, xml ) Need Help??


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).

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://375872]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (7)
As of 2024-04-19 08:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found