Ad hoc creation of objects within a module - Please read to the end 
Author Message
 Ad hoc creation of objects within a module - Please read to the end

Hi all.

I'm writing a module which will act as an object factory but I need some
advice on how to make it generic.

The idea is that you give it the name of a module you wish to create an
object of and it passes back to you a reference to such an object.
Here is a simplified version of the module:
#########
package ObjectFactory;
use Class1;
use Class2;
use Class3;
use Class4;
use Class5;

sub new {

    my $factory = {};
    bless $factory,$class;

Quote:
}

sub createObject {

    $objectType->new;
Quote:
}

###########

Meanwhile in a script:
###########
use ObjectFactory;
my $factory = ObjectFactory->new;
my $object1 = $factory->createObject('Class1');
############

This works fine but can I achieve the same effect without having to "use"
all the various modules that I will potentially be creating objects of in
the ObjectFactory module.

I am trying to avoid the overheads of compiling every single module whenever
I want to use my factory and have the factory only compile the module it
needs instead. (In the above case Class1)

I have tried something to the effect of:
sub create {

    use $objectType;
    return $objectType->new;

Quote:
}

but "use" seems to only like hardcoded strings.

Here's another alternative which I am trying to avoid using:

sub create {

    if ($objectType eq 'Class1') {
        use Class1;
    }
    elsif ($objectType eq 'Class2') {
        use Class2;
    }
    .
    .
    .
    etc.
    return $objectType->new;

Quote:
}

But this is again not ideal as whenever I write a new module I have to amend
the object factory's code to make it aware of this new module.

Thanks for any responses.

Kostis



Wed, 18 Jun 1902 08:00:00 GMT  
 
 [ 1 post ] 

 Relevant Pages 

1. a defense of ad hoc software development

2. Creating ad-hoc subclasses at runtime?

3. Please help XS newbie with object creation

4. eval chokes on indirect object syntax within a module

5. Accessing objects within objects

6. variable creation within a loop

7. Learning OO, object creation query.

8. Trapping Errors on Object Creation

9. Type dispatch in object creation

10. Toplevel destroy hangs after object creation

11. Readers of comp.lang.perl.modules, please read this

12. Readers of comp.lang.perl.modules, please read this

 

 
Powered by phpBB® Forum Software