Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: Factory Pattern

by adrianh (Chancellor)
on Jun 22, 2006 at 07:12 UTC ( [id://556849]=note: print w/replies, xml ) Need Help??


in reply to Factory Pattern

Can anyone recommend any ways of cleaning this up? Is there a more elegant way of doing what I am trying to do? Without using BEGIN blocks and a global hash perhaps? Or without breaking any strictures?

What I'd do is let each animal declare what sound it made...

{ package Animal; use Carp qw( croak ); sub new { bless \my $scalar, shift }; } { package Sheep; use base 'Animal'; sub makes_sound { "baa" } } { package Cow; use base 'Animal'; sub makes_sound { "moo" } } { package Pig; use base 'Animal'; sub makes_sound { "oink" } }

then introspected the class hierarchy to find the animals that did what I wanted

use Devel::Symdump; sub make_animal { my $sound = shift; my @animals_that_make_sound = grep { eval { $_->isa( 'Animal' ) && $_->makes_sound eq $sou +nd } } Devel::Symdump->rnew->packages; die "more than one animal can $sound\n" if @animals_that_make_soun +d > 1; die "no animals $sound\n" unless @animals_that_make_sound; return $animals_that_make_sound[0]->new; } print make_animal( 'oink' );

Log In?
Username:
Password:

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

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

    No recent polls found