Journal(2005) | Blog(2006) | RandomLink | WhoAmI | LiveBookmark | HomePage

<<Previous: module updated  >>Next: Thank God, ubuntu rocks

has $.Examples14 handles 'Perl6';

Category: Perl6   Keywords: delegation handles Perl6

Delegation

Delegation, 中文的意思可以为代表,授权或是委托。
Delegation 能让你在一个 class 或 role 里把另一个对象的方法当成自己的。

例子用于理解

class Dog {
    method wag { 2 }
    method run { 100 }
}
class Wolf {
    method wag { 4 }
}
class Snoopy {
    has $.tail handles 'wag';
}
my $pet = Snoopy.new;
# $pet.wag; 错误,不知道 $.tail 对应哪个类
$pet.tail = Dog.new; # 这里的 $pet 没有继承 Dog 类
$pet.wag; # 2
$pet.tail = Wolf.new; # 将 $.tail 对应到 Wolf
$pet.wag; # 4, $.tail 对应 Wolf, 所以调用 Wolf.wag;

其中最关键的一句就是 has $.tail handles 'wag'; 它使类 Snoopy 产生了一个方法 wag. 而调用 wag 就等同于调用 $.tail.wag 所以这话也就等同于在类里定义了如下代码:

method wag (*@args is context(Lazy)) { $.tail.wag(*@args) }
关键字 handles 的中文意思可以为处理。所以代码 has $.tail handles 'wag' 的字面意思理解可以为“用 $.tail 来处理 wag 调用”。

方法多样化

Want more?

See Synopsis12.

<<Previous: module updated  >>Next: Thank God, ubuntu rocks

Options: +Del.icio.us

Related items Created on 2005-06-02 01:38:59, Last modified on 2005-06-02 01:50:07
Copyright 2004-2005 All Rights Reserved. Powered by Eplanet && Catalyst 5.62.