Singleton Roles at the Muse

I am trying to write a singleton role using Perl and Moose. I understand that the MooseX :: Singleton module is available, but there is always resistance when another CPAN module is required for our project. Having tried this and having worked a little, I would like to understand WHY my method does not work. The singleton role that I wrote is as follows:

package Singleton;
use Moose::Role;

my $_singleInstance;

around 'new' => sub {
    my $orig = shift;
    my $class = shift;
    if (not defined $_singleInstance ){
        $_singleInstance = $class->$orig(@_);
    }
    return $_singleInstance;
};

sub getInstance
{
    return __PACKAGE__->new();
}

1;

, singleton. , (ClassA ClassB, ) Singleton, , $_singleInstance. ClassA- > getInstance, ClassA. ClassB- > getInstance script, ClassA ( getInstance ClassB). Singleton ClassA ClassB, . ?

+5
4

, .

Factory, :

package MyApp::Factory;

my %instances;

# intantiates an object instance if there is none available,
# otherwise returns an existing one.
sub instance
{
    my ($class, $type, @options) = @_;

    return $instances{$type} if $instances{$type};
    $instances{$type} = $type->new(@options);
}

, , MooseX:: Singleton, - , , . , , . Factory ( ), , , .

+3

$_singleInstance , , Singleton. around , $_singleInstance , , , .

:

my %_instances;

around 'new' => sub {
    my $orig = shift;
    my $class = shift;
    if (not defined $_instances{$class} ){
        $_instances{$class} = $class->$orig(@_);
    }
    return $_instances{$class};
};

, , singleton , .

+3

" , MooseX:: Singleton , , CPAN ".

, . dep, MX: Singleton . ? Perl ? , local:: lib, , CPAN Makefile.PL script, CPAN.

+2
source

They share an instance variable. You must select it inside the package using the role.

# find storage for instance
my $iref = \${ "${class}::_instance" };

# an instance already exists; return it instead of creating a new one
return $$iref if defined $$iref;

# no instance yet, create a new one
...
+1
source

All Articles