如何“延迟加载”?用作代表的包?
有没有一种方法可以根据使用的任何委托动态地包含一个包,而不必包含所有不同的委托?
我找到了这个 示例 关于如何使用委托,但它掩盖了我试图理解的细节。这种编写方式基本上都是一个文件...
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");
在我的委托实现中,我根据传递给构造函数的参数使用不同的资源。
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;
没有更好的方法来进行委托,而不必使用所有包(比如某种延迟加载)?
Is there a way I can dynamically include a package based on whatever delegate is used rather than having to include all the various delegates?
I found this example on how to use delegates but it glosses over the details I'm trying to understand. The way this is written it's essentially all one file...
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;
}
Usage:
my $sorter = Sort->new( comparer => SpaceshipCompare->new );
my @sorted = $sorter->my_sort("1one", "0", "43");
In my implementation of a delegate I'm using a different resource based on a parameter that's passed to the constructor.
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() );
}
}
But in order for this to work I have to
use Cache::LocalCache;
use Cache::RemoteCache;
use Cache::MemedCache;
Is there a better way to do delegates without perhaps having to use all the packages (like some kind of lazy load)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在您的示例中,您可以简单地使用 require:
因为
require
是运行时操作时,该类只有在实际需要时才会被加载。如果您的用户传递类名,那么情况会变得更加复杂。您可能需要使用 Module::Load 。In your example, you can simply use require:
Since
require
is a run-time operation, the class won't be loaded until it's actually needed. If your users were passing in class names, then it gets a bit more complicated. You might want to use Module::Load for that.