Perl OOP

1. 模塊/類(包)

建立一個名爲Apple.pm的包文件(擴展名pm是包的缺省擴展名。意爲Perl Module)。
一個模塊就是一個類(包)。php

2. new方法

new()方法是建立對象時必須被調用的,它是對象的構造函數。數組

sub new {
    my $class = shift;
    my $this = {};
    bless $this, $class;
    return $this;
}

this={}/ this。
bless()函數將類名與引用相關聯。從new()函數返回後。$this引用被銷燬。markdown

3. bless方法

構造函數是類的子程序,它返回與類名相關的一個引用。
bless()函數將類名與引用相關聯。app


其語法爲:bless reference [,class]
reference: 對象的引用
class: 是可選項。指定對象獲取方法的包名,缺省值爲當前包名。less

4. 類方法

有兩種方法:靜態方法(如:構造函數)和虛方法。函數


靜態方法第一個參數爲類名。虛方法第一個參數爲對象的引用。oop


虛方法一般首先把第一個參數shift到變量self或this中,而後將該值做普通的引用使用。post


靜態方法直接使用類名來調用。虛方法經過該對象的引用來調用。ui

5. 繼承

@ISA數組含有類(包)名,@INC數組含有文件路徑。this


當一個方法在當前包中未找到時。就到@ISA中去尋找。
@ISA中還含有當前類繼承的基類。

類中調用的所有方法必須屬於同一個類或@ISA數組定義的基類。
@ISA中的每個元素都是一個其餘類(包)的名字。
當類找不到方法時。它會從 @ISA 數組中依次尋找(深度優先)。
類經過訪問@ISA來知道哪些類是它的基類。
e.g.

use Fruit;
our @ISA = qw(Fruit);

6. OOP Sample

Super Class: Fruit.pm

#!/usr/bin/perl -w

use strict;
use English;
use warnings;

package Fruit;

sub prompt {
    print "\nFruit is good for health\n";
}

1;

Sub Class: Apple.pm
Note: Sub class Apple.pm extends super class Fruit.pm via putting Fruit into array @ISA in Apple.pm

#!/usr/bin/perl -w

use strict;
use English;
use warnings;

package Apple;

use Fruit;
our @ISA = qw(Fruit);

sub new {
    my $class = shift;
    my %parm = @_;

    my $this = {};

    $this -> {'name'} = $parm{'name'};
    $this -> {'weight'} = $parm{'weight'};

    bless $this, $class;

    $this -> init();

    return $this;
}

sub init {
    my $reference = shift;
    my $class = ref $reference;

    print "class: $class\n";

    while (my ($key, $value) = each (%$reference))
    {
        print "$key = $value\n";
    }
}

sub order {
    my $class = ref shift;
    my $customer = shift;
    my $address = shift;
    my $count = shift;

    print "\n$customer order $count $class to $address\n";
}

1;

Main Class: Purchase.pl

#!/usr/bin/perl -w

use strict;
use English;
use warnings;

use Apple;

my $apple = new Apple('name' => 'Red Fuji', 'weight' => 300);

$apple -> prompt();

$apple -> order('Zhou Shengshuai', 'ChengDu', 99);

Output:

class: Apple
weight = 300
name = Red Fuji

Fruit is good for health

Zhou Shengshuai order 99 Apple to ChengDu
相關文章
相關標籤/搜索