I apologize in advance for such a basic not really Perl-specific question, but this is such a fantastic forum of minds. I'm glad to be here.
use Factory;
use Fruit;
my $apple = Factory->newObject("Apple");
$apple->doSomethingAnyGenericFruitCanDo();
Mind you, it's so easy to create objects by package name in Perl that the Factory pattern is often unnecessary. You should only use it when it would be inconvenient to specifically use Apple. Usually this is because new class types may be created even after the program's engine code is finished, such as class types created by the application's user.
--
[ e d @ h a l l e y . c c ]
# Initialize a new Z object for each element of @inits
my @obj_array = map {$z->new($_)} @inits;
or if $z is an object of the desired type rather than a class name,
# Initialize a new Z object for each element of @inits
my @obj_array = map {ref($z)->new($_)} @inits;
package Tree;
sub add_item {
my ($self, $item) = @_;
my $parent_node = ...;
$parent_node->add(new Node($item));
}
would be transfored into the following when using a factory:
package Tree;
sub add_item {
my ($self, $item) = @_;
my $node_factory = $self->{node_factory};
my $parent_node = ...;
$parent_node->add($node_factory->create($item));
}
sub set_node_factory {
my ($self, $node_factory) = @_;
$self->{node_factory} = $node_factory;
}
package NodeFactory;
# Overridable
sub create {
shift(@_);
return Node->new(@_);
}
But that's pretty useless in Perl, since it lacks the typing of Java. In Perl, you could just pass a class name ('Node') instead of a factory.
I know some of the basics of OO, and I know how to use Perl as a replacement for awk. I jumped straight into using Object::InsideOut without ever writing up my own simple Perl classes, so I'm ignorant of Perl OO implementation basics. Yesterday on the drive home I figured out that is why some of my questions come from left field and why this advice is more opaque to me than I'd like.
What still mystifies me about your code is the use of the ... operator. This is just a range operator right? I've read every paragraph of perlop that contains the '...' string, but I still don't understand you use of that operator.
Thanks.
my $obj = $factory->create_element( $node_name, @args );
# Check to see if $obj represents a 'foobar' node
if ( $obj->isa( 'foobar' ) ) {
# Do something
}
This is important to me for three reasons:
perlmonks.org content © perlmonks.org and dragonchild, halley, ikegami, je44ery, Roy Johnson
prlmnks.org © 2006 edmund von der burg (eccles & toad)
v 0.03