'a' ); my $p = SpecialEffects->new( "config" =>-6ren">
gpt4 book ai didi

perl - 我可以将一个对象方法别名为不同对象上的不同方法吗?

转载 作者:行者123 更新时间:2023-12-04 19:31:40 25 4
gpt4 key购买 nike

用一个例子更容易解释:

my $o = SpecialEffects->new( "config" => 'a' );
my $p = SpecialEffects->new( "config" => 'b' );

$o->sound(); # aliased to fizz(); same as $o->fizz()
$p->sound(); # aliased to clonk(); same as $p->clonk()

可以在 Perl 中做到这一点吗?也许使用一些 typeglob 或 coderef 技巧?

我试图保留 SpecialEffects界面简单。我不想开始构建对象层次结构。 sound()方法是公开的,只有它的行为可以稍微配置。

我已经知道你可以用 *sound = \&fizz; 来别名但据我所知,这是一个全局性的事情,我希望它封装在对象中。

最佳答案

简单、容易、非向导的方法是只在您的 SpecialEffects 中存储一个方法名称。对象,根据你想要发生的任何事情设置它,并从 sound() 调用它.

package SpecialEffects;

sub new {
my $type = shift;
my %options = @_;
my $self = {};
bless $self, $type;
if($options{config} eq 'a') {
$self->{sound_method} = 'fizz';
} elsif($options{config} eq 'b') {
$self->{sound_method} = 'clonk';
}
return $self;
}

sub sound {
my $self = shift;
my $method_name = $self->{sound_method};
$self->$method_name();
}

sub fizz {
print "fizz\n";
}

sub clonk {
print "clonk\n";
}

如果您想更加灵巧,您可以像方法名称一样轻松地存储和使用 coderef。
package SpecialEffects;

sub new {
my $type = shift;
my %options = @_;
my $self = {};
bless $self, $type;
if($options{config} eq 'a') {
$self->{sound_code} = $self->can('fizz');
} elsif($options{config} eq 'b') {
$self->{sound_code} = $self->can('clonk');
}
return $self;
}

sub sound {
my $self = shift;
my $code = $self->{sound_code};
$self->$code();
}

关于perl - 我可以将一个对象方法别名为不同对象上的不同方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11510973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com