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
In reply to Perl Factory Method Pattern? by osunderdog
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |