How can I implement a singleton class in perl?

What is the best practice for implementing Singletons in Perl?

+7
perl singleton
source share
3 answers

You can use the module Class :: Singleton .

The "Singleton" class can also be easily implemented using the variable my or state (the latter is available with Perl 5.10). But see @Michael 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; } 
+16
source share

If you are using Moose, then MooseX :: Singleton . Its interface is compatible with Class :: Singleton.

+9
source share

Singleton Summary:

  • In most cases, a normal object will work.
  • Be careful with singles.
  • Localize the interaction as much as possible

While singletones are a good idea, I try to just implement a regular object and use it. If it is critical that I have only one such object, I modify the constructor to cause a fatal exception when the second object is created. The various singleton modules seem to do nothing but add a dependency.

I do this because it is easy, it works, and when in some strange future I need to work with the second object in my application, the changes are minimized.

I also like to localize the interaction with my "singleton" objects - keep the interaction as small as possible. Therefore, instead of every object that has direct access to a singleton, I mediate all interaction through my "Application" object. When possible, the application object receives data from "singleton" and passes it as a parameter to the method in other objects. Responses from other objects can also be dropped and passed to singleton. All this helps when I need to make changes to the "singleton" object, and when I want to reuse other objects in another application, which may not be needed or be able to use the original "singleton" object.

+2
source share

All Articles