A minor comment:
The factory probably isn't going to be contained in the base class (though that certainly is a possibility). So the code above is fine if you just turn it into a method in one of your factory classes.
And depending on your solution, it may be a good idea to consider if you want the method to return the new object or the name of the new class.
One thing to remember is that you need to use D1;, use D2; etc so Perl will load the module and be able to find the new() method of the particular class. That means you still have to modify code when you add a new class (unless you script that too).
/J
| [reply] |
My thought was that through the use of require or eval { use ... }, the loading of the module could also be dynamic.
| [reply] [d/l] [select] |
From 'perldoc -f use', I learned
use Module VERSION LIST
use Module VERSION
use Module LIST
use Module
use VERSION
Imports some semantics into the current package from the named module, generally by aliasing certain subroutine or variable names into your package. It is exactly equivalent to
BEGIN { require Module; import Module LIST; }
except that Module *must* be a bareword.
In other words, you will need to check what is passed in.
If you want them to be able to use a path, you will need to use 'require'. This however requires extra security checking to ensure that they don't spoof you by using relative path names.
The following code has only minimally been tested.
package Factory;
use strict;
use My::Baseclass;
my %includedObjects = ();
sub createNew {
my $self = shift;
my $objectName = shift;
unless (exists($includedObjects{$objectName})) {
eval "use My::Baseclass::$objectName";
# eval "require My::Baseclass::$objectName";
if ($@) {
die $@;
};
# else
$includedObjects{$objectName} = 1;
};
if ($objectName->can('new')) {
return $objectName->new(@_); # Pass in any remaining args
} else {
die "'$objectName' does not contain a constructor.";
};
};
| [reply] [d/l] |