简体   繁体   English

如何在Perl中实现单例类?

[英]How can I implement a singleton class in perl?

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

You can use the Class::Singleton module. 您可以使用Class :: Singleton模块。

A "Singleton" class can also be easily implemented using either my or state variable (the latter is available since Perl 5.10). 也可以使用mystate变量轻松实现“ Singleton”类(后者自Perl 5.10起可用)。 But see the @Michael's comment below. 但请参阅下面的@Michael评论。

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 . 如果您使用的是Moose,则可以使用MooseX :: Singleton Its interface is compatible with Class::Singleton. 它的接口与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. 当我需要对“单个”对象进行更改时,以及当我想在另一个不需要或能够使用原始“单个”对象的应用程序中重用其他对象时,所有这些工作都会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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