A recurring pattern that occurs is that you want to construct instances from a class hierarchy based on some typeless data (eg, deserializing a string).

Taking a typical barnyard example:

package Animal; package Sheep; @ISA = ('Animal'); package Cow; @ISA = ('Animal'); package Pig; @ISA = ('Animal');

A new animal wanders into your program and identifies itself with a noise. Either "baa", "moo" or "oink".

You could do this:

sub make_animal { my ($sound) = @_; if ($sound =~ /baa/) { return Sheep->new; } if ($sound =~ /moo/) { return Cow->new; } if ($sound =~ /oink/) { return Pig->new; } }

The problem is that each time you define a new animal, you have to update your make_animal function.

What would be better is if within the class somehow the animal "registered" itself against the sound it makes.

We can do that by creating a global hash, and then each animal class enters itself into this hash:

package Sheep; BEGIN { our %::animal_sounds; $::animal_sounds{'baa'} = 'Sheep'; }

And then the make_animal function becomes:

sub make_animal { my ($sound) = @_; foreach my $sounds_like (keys %::animal_sounds) { if ($sound =~ /$sounds_like/) { return ($::animal_sounds{$sounds_like})->new; } } }

This function then would not change when a new Animal is added to the hierarchy.

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?

Is there a CPAN module that does something similiar to this?

-Andrew.


In reply to Factory Pattern by tomazos

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.