�������!
Advanced Perl Programming, 2nd Ed.
Simon Cozens
[ˮ��:����Perl�ץ�����ߥ���2��]
�Ȥ������Ȥ� Class::SingletonMethod �ߤ����˥��饹̾����������㤦�褦����ˡ�ʳ��� Singleton Method (�ðۥ᥽�å�) ��¸�������ˡ�Ϥʤ����ʤ���
�����Ƿ�̿�ʥҥ祦��(���äƤʤ��ͤϾ夫����äƤ����ޤ�)���ɼԤϡ������פ��Ĥ��Ȼפ��Τ����ɡ�
package Object::SingletonMethod; use 5.008001; use strict; use warnings; use Carp; use Data::Dumper; our $VERSION = '0.01'; our $DEBUG = 1; my %Method; sub singleton_method { my $self = shift; my ( $method, $subref ) = @_; ref $subref eq 'CODE' or croak '$obj->singleton_method(name => sub{...})'; $Method{ $self + 0 }{$method} = $subref; } sub can { my ( $self, $method ) = @_; my $subref = $Method{ $self + 0 }{$method}; return $subref if $subref; return $self->SUPER::can($method); } sub DESTROY { my $self = shift; $DEBUG and carp "Destroing $self"; delete $Method{ $self + 0 }; } sub AUTOLOAD { my $self = shift; my $method = our $AUTOLOAD; $method =~ s/.*:://; $DEBUG and carp "($self)->$method"; if ( my $subref = $Method{ $self + 0 }{$method} ) { $subref->( $self, @_ ); } else { my $pkg = ref $self; croak qq(Can't locate object method "$method" via package "$pkg"); } } 1; __END__
�ʲ��Ǽ¾ڡ�
# use strict; use warnings; use Data::Dumper(); package Foo; use base 'Object::SingletonMethod'; sub new { my $class = shift; bless {@_} => $class; } sub dump{ my $self = shift; local ($Data::Dumper::Terse) = 1; return Data::Dumper::Dumper($self); } package main; my $foo = Foo->new; my $far = Foo->new; $foo->singleton_method( inc => sub { my $self = shift; $self->{_inc}++; $self; } ); $foo->inc; $foo->inc; print "foo can inc? ", ( $foo->can('inc') ? "Yes" : "No" ), "\n"; print "foo can new? ", ( $foo->can('new') ? "Yes" : "No" ), "\n"; print "foo can pee? ", ( $foo->can('pee') ? "Yes" : "No" ), "\n"; print "far can inc? ", ( $far->can('inc') ? "Yes" : "No" ), "\n"; print "far can new? ", ( $far->can('new') ? "Yes" : "No" ), "\n"; print "far can pee? ", ( $far->can('pee') ? "Yes" : "No" ), "\n"; print $foo->dump;
�¤Ϥ��������my variable��$object + 0�ò¥¡ï¿½ï¿½Ë¤ï¿½ï¿½Æ¥ï¿½ï¿½ó¥¹¥ï¿½ï¿½ó¥¹¤ò¤·¤Þ¤ï¿½ï¿½ï¿½ï¿½ï¿½È¤ï¿½ï¿½ï¿½ï¿½ï¿½Ë¡ï¿½Ï¡ï¿½Inside-Out Object�ȸƤФ�롢���Ū������Perl��Object����ˡ�ǡ������Damianή��Ű��Ū�˾��ڤ������Τ�Class::Std�����졢���Ĥ��ܺٲ���(�ġ���ź��!)����Ĥ������ɡ��ԤƤʤ��ͤϥ��󥰥ơ���ʥ���ܢ��ò¤¸¤Ã¤ï¿½ï¿½ê¤ªï¿½É¤ß¤ï¿½ï¿½ì¡£
Dan the Man with Too Many Ways to Do Too Many Things
���Υ֥����˥����Ȥ���ˤ�����������ɬ�פǤ���
��������������
���ε����ˤϵ��ĥ桼�����������Ȥ��Ǥ��ޤ���