在Perl中似乎有很多方法可以实现多态,但是它们对我来说都是“ hacky”。我对Perl有点陌生,所以我可能会误解它,但是我发现大多数示例会使您的代码变得难以辨认并且引起争议。
假设您有一个小部件类,其中包含所有小部件都需要的一些数据和方法。还有一些小部件类型(例如,日历,日程表等)。他们需要彼此通信(通过父容器类)。
玩命名空间并使小部件成为原型值得吗?
我应该在实例化时为每个小部件提供对一个对象(一种类型)的引用吗?
只需忘记类型是对象,然后将小部件变成大型类即可,根据设置的类型,每个实例仅使用几种方法。还有吗
我来自C / C ++背景,发现很难决定Perl编程模型。
另外,我对类型安全性要求不高,也没有私人成员的要求。该项目是具有几个开发人员的中型Web应用程序,可移植性不是其他项目的重点。但是,无需解密Perl hack即可轻松进行扩展将很有用。
“现代Perl”方法可能被定义Widget
为角色。可以将角色视为类似于mixin,接口或抽象基类。使用Moose :: Role或其更轻量的替代项之一(Moo :: Role,Role :: Tiny)执行此操作。
{
package Widget;
use Moo::Role;
sub some_common_method {
my $self = shift;
...;
}
sub another_common_method {
my $self = shift;
...;
}
# Here we're indicating that all Widgets must
# have a method called yet_another_common_method,
# but we're not defining how that method should
# be implemented.
requires "yet_another_common_method";
}
现在,您可以创建一个组成该角色的类:
{
package Calendar;
use Moo;
with "Widget";
# Here's a member variable.
has year => (is => "ro", required => 1);
# Widget requires us to implement this.
sub yet_another_common_method {
my $self = shift;
...;
}
# We can override Widget's implementation
# of this method.
sub some_common_method {
my $self = shift;
...;
}
# We can install hooks ("method modifiers")
# to Widget's methods.
before another_common_method => sub {
my $self = shift;
print STDERR "Calendar ", $self->year, ": another_common_method() was called.\n";
};
}
还有一个:
{
package Schedule;
use Moo;
with "Widget", "Editable";
sub yet_another_common_method {
my $self = shift;
...;
}
}
并使用以下类:
my $calendar = Calendar->new( year => 2014 );
my $schedule = Schedule->new;
my @widgets = ($calendar, $schedule);
for (@widgets) {
$_->some_common_method if $_->does('Widget');
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句