面向对象下面几步

来源:互联网 发布:天竺棉和水洗棉 知乎 编辑:程序博客网 时间:2024/05/21 11:36
高效的属性存储:我们一向使用散列表来存储对象属性,我们这样做有几个好的理由:1.每个属性都是自我描述的(也就是说,每个属性的名字和类型可以很容易的从对象中获取),这样可以很容易的来编写可读性好的代码。它还可以使模块无需对象显示合作就能够进行自动的对象持续性存储或对象的可视化。2.位于继承层次中的每个类都可以自由独立的添加属性ObjectTemplate:使用数组来存储属性:这一节展示的模块使用数组来存储属性(但是不是那种每个对象一个数组的方式)注意:Perl 允许你不存在用法歧义的情况下,省略任何调用方法的括号。与前面的例子一样,任何跟在箭头后面的单词都被当作是一个方法。Vsftp:/root/perl/19# cat ObjectTemplate.pm package ObjectTemplate;  require Exporter;      @ISA = qw(Exporter);      @EXPORT_OK = qw(new position); sub new {         my $self = {};             my $class = shift;  ##第一个参数类的名字;         my $self ={@_};         bless $self,$class;    return $self;};  sub position {        my $self=shift;        my $Actress=shift;        return "$Actress.length$Actress"         };1;Vsftp:/root/perl/19# cat Employee.pm package Employee;use ObjectTemplate qw/new position/;1;Vsftp:/root/perl/19# cat a1.pl unshift(@INC,"/root/perl/19");use Employee;use Data::Dumper;$obj = Employee->new("name"=>"Normae Jean",                     "age" =>25                     )  ##new()方法由ObjectTemplate创建;print Dumper($obj);print "\n";print $obj->{name};print "\n";print $obj->{age};print "\n";print $obj->position("Actress");Vsftp:/root/perl/19# perl a1.pl $VAR1 = bless( {                 'name' => 'Normae Jean',                 'age' => 25               }, 'Employee' );Normae Jean25Actress.lengthActressVsftp:/root/perl/19# Vsftp:/root/perl/19# cat Employee.pm package Employee;use ObjectTemplate qw/new position/;sub promote {    my $self=shift;    my $current_position=$self->position(); ##获取属性    my $next_position = $current_position."abc123";   $self->position($next_position);     };1;Vsftp:/root/perl/19# cat a1.pl unshift(@INC,"/root/perl/19");use Employee;use Data::Dumper;$obj = Employee->new("name"=>"Normae Jean",                     "age" =>25                     )  ##new()方法由ObjectTemplate创建;print Dumper($obj);print "\n";print $obj->{name};print "\n";print $obj->{age};print "\n";print $obj->position("Actress");print "\n";print $obj->promote();Vsftp:/root/perl/19# perl a1.pl $VAR1 = bless( {                 'name' => 'Normae Jean',                 'age' => 25               }, 'Employee' );Normae Jean25Actress.lengthActress.lengthabc123.length.lengthabc123Vsftp:/root/perl/19# 

0 0
原创粉丝点击