perl - 如何将 "lazy load"包用作委托(delegate)?

标签 perl oop delegates moose

有没有一种方法可以根据使用的任何委托(delegate)动态地包含一个包,而不必包含所有不同的委托(delegate)?

我找到了这个example关于如何使用委托(delegate),但它掩盖了我试图理解的细节。这种编写方式基本上都是一个文件......

package Compare;
use Moose::Role;
requires 'compare';


package SpaceshipCompare;
use Moose;
with 'Compare';  

sub compare { my ($a, $b) = @_; return $a <=> $b }

package Sort;
use Moose;

has 'comparer' => (
    is       => 'ro',
    does     => 'Compare',
    handles  => 'Compare',
    required => 1,
);

sub my_sort {
    my ($self, @list) = @_;
    return sort { $self->compare($a, $b) } @list;
}

用法:

my $sorter = Sort->new( comparer => SpaceshipCompare->new );
my @sorted = $sorter->my_sort("1one", "0", "43");

在委托(delegate)的实现中,我根据传递给构造函数的参数使用不同的资源。

  sub BUILD{
    my($this,$args) = @_;

        if($args->{cachedDataSource} eq 'local'){

            $this->setDataStore( Cache::LocalCache->new() ); 

        }

        if($args->{cachedDataSource} eq 'remote'){

            $this->setDataStore( Cache::RemoteCache->new() ); 

        }


        if($args->{cachedDataSource} eq 'memd'){

            $this->setDataStore( Cache::MemedCache->new() ); 

        }

}

但是为了让它发挥作用,我必须

use Cache::LocalCache;
use Cache::RemoteCache;
use Cache::MemedCache;

是否有更好的方法来进行委托(delegate),而不必使用所有包(例如某种延迟加载)?

最佳答案

在您的示例中,您可以简单地使用 require :

sub BUILD{
    my($this,$args) = @_;

        if($args->{cachedDataSource} eq 'local'){
            require Cache::LocalCache;
            $this->setDataStore( Cache::LocalCache->new() ); 
        }

        if($args->{cachedDataSource} eq 'remote'){
            require Cache::RemoteCache;
            $this->setDataStore( Cache::RemoteCache->new() ); 
        }

        if($args->{cachedDataSource} eq 'memd'){
            require Cache::MemedCache;
            $this->setDataStore( Cache::MemedCache->new() ); 
        }
}

由于 require 是一个运行时操作,因此在实际需要该类之前不会加载该类。如果您的用户传递类名,那么情况会变得更加复杂。您可能想使用 Module::Load为此。

关于perl - 如何将 "lazy load"包用作委托(delegate)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8075372/

相关文章:

perl - 如何在 Cygwin 上为 Perl 设置 'use diagnostics'?

perl - 为什么正面前瞻会导致在我的 Perl 正则表达式中进行捕获?

C++ 子类中某些方法的高效继承

regex - Perl 正则表达式匹配表情符号

Perl 内存使用分析和泄漏检测?

python - OOP 和 Python 的新手 -- 关于存储大量对象的问题

php - Controller 可以有数据库查询(MySQL)吗?如果是,什么时候?

c# - 是否可以为 Func<T1,T2,....> 参数的部分提供智能感知的 xml 注释?

ios - 需要开发Custom Delegate进行API调用

ios - 自定义委托(delegate)回调