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!
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|