What's the best practice for implementing Singletons in Perl?
You can use the Class::Singleton module.
A "Singleton" class can also be easily implemented using either my
or state
variable (the latter is available since Perl 5.10). But see the @Michael's comment below.
package MySingletonClass;
use strict;
use warnings;
use feature 'state';
sub new {
my ($class) = @_;
state $instance;
if (! defined $instance) {
$instance = bless {}, $class;
}
return $instance;
}
If you're using Moose, then MooseX::Singleton. Its interface is compatible with Class::Singleton.
Singleton Summary:
- Most of the time a normal object will work.
- Be careful with singletons.
- Localize interaction as much as possible
While singletons are a nice idea, I tend to just implement a normal object and use it. If it is critical that I only have one such object, I'll modify the constructor to throw a fatal exception when the second object is created. The various singleton modules don't seem to do much besides add a dependency.
I do this because it is easy, it works, and when in some weird future I need to work with a second object in my app, the changes are minimized.
I also like to localize interaction with my 'singleton' objects--keep interaction in as few places as possible. So instead of every object having direct access to the singleton, I mediate all interaction through my "Application" object. Whenever possible, the application object gets data from the 'singleton', and passes it as a parameter to the method in the other objects. Responses from other objects may also be munged and passed to the 'singleton'. All this effort helps when I need to make changes in the 'singleton' object, and when I want to reuse other objects in another app that may not need or be able to use the original 'singleton' object.
Here an example of a singleton class.
package MySingletonClass;
use strict;
use warnings;
# Do no use use feature 'state'; before perl 5.17
my $instance; # = null ;
sub new {
my ($class) = @_;
if (! defined $instance) {
$instance = bless {}, $class;
}
return $instance;
}
© 2022 - 2024 — McMap. All rights reserved.