package BankAccount;
use Moose;
has 'balance' => (isa => 'Int', is => 'rw', default => 0);
sub deposit {
my ($self, $amount) = @_;
$self->balance($self->balance + $amount);
}
sub withdraw {
my ($self, $amount) = @_;
my $current_balance = $self->balance();
($current_balance >= $amount)
|| confess "Account overdrawn";
$self->balance($current_balance - $amount);
}
package CheckingAccount;
use Moose;
extends 'BankAccount';
has 'overdraft_account' => (isa => 'BankAccount', is => 'rw');
before 'withdraw' => sub {
my ($self, $amount) = @_;
my $overdraft_amount = $amount - $self->balance();
if ($self->overdraft_account && $overdraft_amount > 0) {
$self->overdraft_account->withdraw($overdraft_amount);
$self->deposit($overdraft_amount);
}
};
知识点:
属性的类型可以是另外一个类的名字
新modifier before,他在父类函数之前调用定义的sub
相当于
sub withdraw {
my ($self, $amount) = @_;
my $overdraft_amount = $amount - $self->balance();
if ($self->overdraft_account && $overdraft_amount > 0) {
$self->overdraft_account->withdraw($overdraft_amount);
$self->deposit($overdraft_amount);
}
$self->SUPER::withdraw($amount);
}

没有评论:
发表评论