Perl中有效建立Getter 和Setter的方法

物理狂人發表於2012-05-07
利用Class::MethodMaker可以有效避免重新寫很多getter和setter的程式碼,具體如下:

package Animal;
use Class::MethodMaker
new_with_init => 'new',
get_set => [ -eiffel => [qw(color height name age)]],
abstract => [qw(sound)],
;
sub init {
my $self = shift;
$self->set_color($self->default_color);
}

sub named {
my $self = shift->new;
$self->set_name(shift);
$self;
}

sub speak {
my $self = shift;
print $self->name, '  goes ', $self->sound, "\n";
}

sub eat {
my $self = shift;
my $food = shift;
print $self->name, " eats $food\n";
}

sub default_color {
'brown';
}

生成函式new會呼叫init函式,eiffel中為需要建立的setter和getter物件

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/24104518/viewspace-722907/,如需轉載,請註明出處,否則將追究法律責任。

相關文章