gpt4 book ai didi

Perl OO 使用 Moose - 编写委托(delegate)示例的最佳方式?

转载 作者:行者123 更新时间:2023-12-04 14:05:53 25 4
gpt4 key购买 nike

Perl 的 Moose 与其他对象系统不同,因此如何将其他语言已知的示例翻译成 Moose 术语并不总是很清楚。考虑以下 Rectangle 和 Square 的 Java 示例,其中 Square 实例(正方形是特殊的矩形)将对 area() 的调用委托(delegate)给它持有私有(private)引用的 Rectangle 实例。

package geometry;
class Rectangle {
private int x;
private int y;
public Rectangle(int x, int y) {
this.x = x;
this.y = y;
}
public int area() {
return x * y;
}
}
class Square {
private Rectangle rectangle;
public Square(int a) {
this.rectangle = new Rectangle(a, a);
}
public int area() {
return this.rectangle.area();
}
}
public class Main {
public static void main( String[] args ) {
int x, y;
if ( args.length > 1 ) {
x = Integer.parseInt( args[0] );
y = Integer.parseInt( args[1] );
}
else {
x = 3;
y = 7;
}
Rectangle r = new Rectangle( x, y );
System.out.println( r.area() );
Square sq1 = new Square( x );
System.out.println( sq1.area() );
Square sq2 = new Square( y );
System.out.println( sq2.area() );
}
}

我拼凑了以下 Perl/Moose/Mouse 版本,我不确定这是不是正确的做事方式,所以我将其提交给聚集在这些大厅的专家公会的判断:
package Rectangle;
use Mouse;
has [ qw( x y ) ], is => 'ro', isa => 'Int';

sub area {
my( $self ) = @_;
return $self->x * $self->y;
}

package Square;
use Mouse;
has x => is => 'ro', isa => 'Int';
has rectangle => is => 'ro', isa => 'Rectangle';

# The tricky part: modify the constructor.
around BUILDARGS => sub {
my $orig = shift;
my $class = shift;
my %args = @_ == 1 ? %{ $_[0] } : @_;
$args{rectangle} = Rectangle->new( x => $args{x}, y => $args{x} );
return $class->$orig( \%args );
};

sub area { $_[0]->rectangle->area } # delegating

package main;
use strict;
my $x = shift || 3;
my $y = shift || 7;
my $r = Rectangle->new( x => $x, y => $y);
my $sq1 = Square->new( x => $x );
my $sq2 = Square->new( x => $y );
print $_->area, "\n" for $r, $sq1, $sq2;

这行得通,但由于我没有看到太多 Moose 在行动,我只是不确定这是要走的路,或者是否有更简单的方法。感谢您提供任何反馈,或提供更多 Moose 用户级别讨论的建议。

最佳答案

虽然我不确定这是最佳实践,但我能想到的最佳翻译可能是这样的:

package Rectangle;
use Mouse;
has [ qw( x y ) ], is => 'ro', isa => 'Int';

sub area {
my( $self ) = @_;
return $self->x * $self->y;
}

package Square;
use Mouse;
has x => is => 'ro', isa => 'Int';
has rectangle =>
is => 'ro',
isa => 'Rectangle',
lazy_build => 1,
handles => [ 'area' ];

sub _build_rectangle {
my $self = shift;
Rectangle->new(x => $self->x, y => $self->x);
}
handles in rectangle 属性会自动为您建立对区域的委托(delegate)。

关于Perl OO 使用 Moose - 编写委托(delegate)示例的最佳方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5363409/

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