简体   繁体   中英

How can I implement a singleton class in perl?

在Perl中实现Singletons的最佳实践是什么?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM