Here's my fevered imaginings.

With more than two derived classes, I'd use a hash or perhaps an array in B holding references to the constructors of the derived classes. It depends on how much the program may be extended in the future.

package B; sub new { my $class = shift; # ignore my $type = shift; if ($type == 1) { return D1->new(@_); } elsif ($type == 2) { return D2->new(@_); } else { return undef; } } # more as appropriate package D1; @D1::ISA = qw( B ); sub new { # paranoia check # you may not want this and I haven't tested it anyway return unless caller eq 'B'; # more as appropriate } package D2; @D2::ISA = qw( B ); sub new { # you may not want this and I haven't tested it anyway return unless caller eq 'B'; }

Update: You might have to do something like the following:

package B; my @models; # factory model, get it? sub add { my $self = shift; my $child_coderef = shift; push @models, $child_coderef; } sub new { my $class = shift; # ignore my $type = shift; return unless $type; my $child_coderef = @models[$type - 1]; return unless defined &$child_coderef; return $child_coderef->(@_); } package D3; @D3::ISA = qw( B ); use B; # gotta be done here B->add(\&new); sub new { # etc }
That's where I'd start my experimenting. Good luck!

In reply to Re: Factory Pattern for Class Heirarchy by chromatic
in thread Factory Pattern for Class Heirarchy by dcorbin

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.