views:

180

answers:

2

Why to use factory to wrap a constructor in Perl? An example would help.

+5  A: 

Same exact reason you'd use a factory in any other OO language.

See http://en.wikipedia.org/wiki/Factory_method_pattern

Factory methods are common in toolkits and frameworks where library code needs to create objects of types which may be subclassed by applications using the framework.

Parallel class hierarchies often require objects from one hierarchy to be able to create appropriate objects from another.

Factory methods are used in test-driven development to allow classes to be put under test[2]. If such a class Foo creates another object Dangerous that can't be put under automated unit tests (perhaps it communicates with a production database that isn't always available), then the creation of Dangerous objects is placed in the virtual factory method createDangerous in class Foo. For testing, TestFoo (a subclass of Foo) is then created, with the virtual factory method createDangerous overridden to create and return FakeDangerous, a fake object. Unit tests then use TestFoo to test the functionality of Foo without incurring the side effect of using a real Dangerous object.

Further details on Perl factory pattern:

http://www.perl.com/pub/a/2003/08/15/design3.html

and

http://www.perldesignpatterns.com/?FactoryObject

DVK
+4  A: 

A common use of a Factory is to produce a object when you don't know which type you'll need ahead of time. The factory figures out which constructor to call based on the situation.

Just as an example, let's say you want to make a class to download files, but you don't know ahead of time how you'll can fetch a file. Maybe it's FTP, HTTP, SVN, or something else. You have a Downloader class that takes a URL of any type and gives you an object:

 my $object = Downloader->new( $some_url );

You don't know the type of this object, but you don't care either. All the objects it creates know how to respond to store_in_directory, so you call the method without knowing the type of the particular object:

 $object->store_in_directory( $dir );

And there you go. The new factory let subclasses (or something else), create $object. It makes the interface simpler because at the application level you don't worry about choosing the right class.

One of the nice features about Perl is that you don't have to hardcode class names. You can do something like this, where you use a string defined at runtime to build the object:

 sub new {
      my( $class, @args ) = @_;

      my $output_class = $class->choose_the_right_implementing_class;

      my $output_object = $output_class->new;
      }
brian d foy