On Mon, Jun 29, 2009 at 08:16, Steve Bertrand<[email protected]> wrote:
> Thomas Bätzler wrote:
>> Steve Bertrand <[email protected]> asked:
>>> Can anyone suggest a perldoc or recommended practise that will help me
>>> in regards to:
>>>
>>> I have numerous classes, all suited to a different object-type or
>>> function.
>>>
>>> When I instantiate an object (all classes are under the same Module::
>>> umbrella), I *think* what I want to do is create an 'error' object, but
>>> I want that _specific_ instance of the Error object carried along with
>>> ALL objects created during the time the life-cycle is in operation.
>>
>> You could use Class::Singleton [1] as a parent of your error handling class. 
>> That way, you can instantiate your error handling object in each of your 
>> classes in any order you like, and it'll always be the same object.
>
> Nice! That looks like it's exactly what I'm after.
>
> It will certainly save me from passing the object around as a parameter.
>
> Thanks!
>
> Steve
>
>

I distrust the singleton pattern (there are almost never just one of a
resource), so I tend to go with a caching pattern that yields similar
results:

package Foo;

our %instances;
sub new {
    my $class = shift;
    my $self  =  { @_ };

    my $key   = join "-", @{self}{sort keys %$self};
    if (exists $instances{$key}) {
        return $instances{$key};
    }
    return $instances{$key} = bless $self, $class;
}

If called with the same arguments it returns the same object.  This
means that latter, if you find that you really need two of these
objects instead of [one][2], you can just pass different arguments to
get other instances.

You may also want to read [Design Patterns][1] by Erich Gamma, Richard
Helm, Ralph Johnson and John Vlissides.

[1]: http://en.wikipedia.org/wiki/Design_Patterns_(book)
[2]: I remember one place where they were using a singleton to
represent the screen, boy were they hosed by the advent of multiple
monitors.

-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/


Reply via email to