hardburn has asked for the wisdom of the Perl Monks concerning the following question:
I'm trying to write a Factory pattern in Perl6, and I need to pass the same arguments to the constructor of each class. All the examples of Perl6 Factories out there right now seem to have neglected trying to pass arguments.
In Perl5, I would probably set a variable to hold the classname, and then pass the args after we figure out where we want to go.
my $class = $type == 0 ? 'ClassA' : $type == 1 ? 'ClassB' : 'ClassC'; my $obj = $class->new( foo => 1, bar => 2 );
Alternatively, you can wrap up the arguments and rely on list flattening to take care of it:
my %args = ( foo => 1, bar => 2 ); my $class = $type == 0 ? ClassA->new( %args ) : $type == 1 ? ClassB->new( %args ) : 'ClassC';
My first attempt in Perl6 followed the first method above:
my $class; given $type { when 0 { $class = ClassA } when 1 { $class = ClassB } default { $class = ClassC } } my $obj = $class.new( foo => 1, bar => 1 );
But this resulted in an object from Any, not the class I wanted.
I also took a stab at the second method, attempting to use the | list flattening operator:
my @args = ( foo => 1, bar => 1 ); my $obj; given $type { when 0 { $obj = ClassA.new( |@args ) } when 1 { $obj = ClassB.new( |@args ) } default { $obj = ClassC.new( |@args ) } }
Along with a few variations, most of which failed with Default constructor for 'ClassA' only takes named arguments.
Help for either option would be enlightening.
"There is no shame in being self-taught, only in not trying to learn in the first place." -- Atrus, Myst: The Book of D'ni.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Factory Pattern in Perl6
by raiph (Deacon) on May 14, 2016 at 03:26 UTC | |
by hardburn (Abbot) on May 18, 2016 at 00:32 UTC | |
by raiph (Deacon) on May 18, 2016 at 05:17 UTC | |
by hardburn (Abbot) on May 18, 2016 at 22:00 UTC | |
by raiph (Deacon) on May 19, 2016 at 21:14 UTC | |
|