in reply to Do I need a Factory Class At This Point?

Factories are usually used by objects to create child objects. The purpose of the factory is to avoid having to hardcode a class name. For example,
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 easily accept a class name (e.g. 'Node') or a code ref (e.g. sub { Node->new(@_) }) instead of a factory.

Replies are listed 'Best First'.
Re^2: Do I need a Factory Class At This Point?
by jffry (Hermit) on Feb 03, 2006 at 17:45 UTC
    OK, I am getting enough of what you are telling me to understand your point.

    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.

      Such diligence! But in this case, ... simply means "There's code missing here." How one finds where to insert a node into a tree wasn't relevant to the topic at hand.