Dallaylaen has asked for the wisdom of the Perl Monks concerning the following question:
Hello dear esteemed monks,
I have a class that is read-only. It does have parameters, but for the most cases a default instance would fit. So I'd like to avoid unneeded initialization and just return $ONE_AND_TRUE_INSTANCE if such exists and no parameters are given to new().
Here's how I would've done this outside Moo/Moose:
my $ONE_TRUE_INSTANCE = __PACKAGE__->new; sub new { my ($class, %args) = @_; return $ONE_TRUE_INSTANCE if ($ONE_TRUE_INSTANCE and $class eq __PACKAGE__ and !%args); # normal constructor here ... };
Can the same be achieved with Moo? How can my example code be improved? Maybe there's a proper architectural solution and/or pattern for this?
Thank you,
UPDATE: actually I can do this with Moo, so the question remains - what can be fixed in architecture to avoid the need for "defaulton":
package Defaulton; use Moo; has foo => is => ro => default => sub { 42 }; my $INST = __PACKAGE__->new; around new => sub { my ($orig, $class, @args) = @_; return $INST if $INST and $class eq __PACKAGE__ and !@args; return $class->$orig(@args); }; 1;
|
|---|