Moose is a software tool with a Singleton Method feature. It allows developers to define classes that only have one instance in a program. This can simplify code and improve performance by reducing redundant objects.
To begin, you must import the module and create a new package. Then create an instance of the package to which you want to add a Singleton method. In the example below, the package is called "Baz."
# Simple usage example....
package Baz;
use MooseX::SingletonMethod; # new;
my $foo = Baz->new;
The Singleton method can be added to the instance using the add_singleton_method function. The example below shows how to add a Singleton method called "baz" to $baz.
$baz->add_singleton_method( baz => sub { 'baz!' } );
Once the method is added, you can call it as shown below.
say $baz->baz; # => 'baz'
However, calling the method on the package itself generates an error.
say $foo->baz; # ERROR: Can't locate object method "baz"....
To avoid this, you should use the MooseX::SingletonMethod::Role instead of MooseX::SingletonMethod. To apply the role, modify your package as shown below.
package Baz;
use Moose;
with 'MooseX::SingletonMethod::Role';
no Moose;.
Overall, MooseX::SingletonMethod is an excellent module for adding Singleton methods to Moose. Whether you use the module directly or via a role, it is easy to use, and the impact on your code will be noticeable.
Version 0.03: N/A