osunderdog has asked for the wisdom of the Perl Monks concerning the following question:
Perlmonks, I have a matter for your consideration:
I am looking for a pattern for a Class Factory Method pattern in perl. I am developing a class that I expect to have at least three subclasses that can be instanciated. The base class will define the interface and each of the subclass will provide a different implementation for the platform where class is invoked. I have written several of these, but each time I wonder if there is a pattern out there that avoids some of the pitfalls or, worse yet, there are pitfalls have yet to encounter!
I know that there is a Package to do this via inheritance: Class::Factory However I do not have access to that Class in our standard Perl installation and I would like to minimize external dependencies.
For the base class, here's what I have:
package ProcInfo; use Carp; use strict; use warnings; our $VERSION = '0.01'; sub new { my $class = shift; my $self = {}; bless $self, $class; $self->_init(); return $self; } sub _init { my $self = shift; my $osModule = "ProcInfo_$^O"; # Load the subclass if it isn't already loaded. eval "require $osModule"; if($@) { croak "Could not load OS ProcInfo Module:$osModule. [$@]"; } # rebless self using subclass. bless $self, $osModule; $self->_init(@_); return $self; } sub method_1 { return 1; } 1;
Some question I have about the base class implementation:
The skeleton for each sublcass would looking like this and it would be stored in ProcInfo_linux.pm:
package ProcInfo_linux; use strict; use warnings; use base qw|ProcInfo|; our $VERSION = '0.01'; sub _init { my $self = shift; return $self; } sub method_1 { return 1; } 1;
Finally, here is my test script (ProcInfo.t):
use Test::More tests => 3; BEGIN { use_ok('ProcInfo') }; my $pInfo = new ProcInfo; is(ref($pInfo), "ProcInfo_$^O", "Factory new Works"); ok($pInfo->method_1());
Any suggestions or comments on this implementation would be appreciated!
Janitored by Arunbear - added readmore tags, as per Monastery guidelines
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Perl Factory Method Pattern?
by dragonchild (Archbishop) on Oct 11, 2004 at 19:42 UTC | |
by pg (Canon) on Oct 11, 2004 at 20:02 UTC | |
|
Re: Perl Factory Method Pattern?
by sandfly (Beadle) on Oct 11, 2004 at 22:51 UTC | |
|
Re: Perl Factory Method Pattern?
by SpanishInquisition (Pilgrim) on Oct 11, 2004 at 20:10 UTC | |
by hardburn (Abbot) on Oct 11, 2004 at 20:43 UTC | |
by SpanishInquisition (Pilgrim) on Oct 12, 2004 at 13:14 UTC | |
|
Minimizing dependencies (was: Perl Factory Method Pattern?)
by lachoy (Parson) on Oct 13, 2004 at 00:40 UTC | |
by osunderdog (Deacon) on Oct 27, 2004 at 18:52 UTC |