有没有一种方法可以根据使用的任何委托(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/