Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: $foo = "Foo::Bar"; $foo->new() works?

by dws (Chancellor)
on Jan 23, 2005 at 04:18 UTC ( [id://424335]=note: print w/replies, xml ) Need Help??


in reply to $foo = "Foo::Bar"; $foo->new() works?

One reason that it is a Very Good Thing that it works this way is that it allows you to write things like subclassable factories, where the class of the thing being constructed is determined by the factory subclass.

package Factory; sub makeThing { my ($class, @args) = @_; my $thingClass = $class->thingClass; my $thing = $thingClass->new(@args); $class->magicStuff($thing); return $thing; } sub thingClass { 'Thing' } sub magicStuff { my ($class, $thing) = @_; # pretend there's generic magic stuff here }

Now, to change the class of the thing being constructed, you simply subclass the factory class and override one method.

package SpecialFactory; use base qw(Factory); sub thingClass { 'SpecialThing' }

Now, Factory->makeThing gives you a Thing, and SpecialFactory->makeThing gives you a SpecialThing.

Replies are listed 'Best First'.
Re^2: $foo = "Foo::Bar"; $foo->new() works?
by Thelonious (Scribe) on Jan 23, 2005 at 15:29 UTC
    or you could even

    sub thingClass { ref $_[0] }

    in the base class, and forget about having to create overrides.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (2)
As of 2024-04-26 04:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found