in reply to Re: Factory Pattern for Class Heirarchy
in thread Factory Pattern for Class Heirarchy

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

  • Comment on RE: Re: Factory Pattern for Class Heirarchy

Replies are listed 'Best First'.
RE: RE: Re: Factory Pattern for Class Heirarchy
by dcorbin (Sexton) on Oct 08, 2000 at 23:45 UTC
    My thought was that through the use of require or eval { use ... }, the loading of the module could also be dynamic.

      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."; }; };
        if ($objectName->can('new')) { return $objectName->new(@_); # Pass in any remaining a +rgs } else { die "'$objectName' does not contain a constructor."; };
        This is both overkill and inaccurate. A constructor does not have to be named new, so the die message is inaccurate. And it's going to die anyway if you can't find the method, so just use:
        return $objectName->new(@_); # I hope they know how!

        -- Randal L. Schwartz, Perl hacker