/
perlootut.pod
1825 lines (1217 loc) · 52.2 KB
/
perlootut.pod
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
=encoding euc-jp
=for comment
Consistent formatting of this file is achieved with:
perl ./Porting/podtidy pod/perlootut.pod
=head1 NAME
=begin original
perlootut - Object-Oriented Programming in Perl Tutorial
=end original
perlootut - Perl でのオブジェクト指向プログラミングのチュートリアル
=head1 DATE
=begin original
This document was created in February, 2011, and the last major
revision was in February, 2013.
=end original
この文書は 2011 年 2 月に作成され、最後に大きく見直されたのは 2013 年
2 月です。
=begin original
If you are reading this in the future then it's possible that the state
of the art has changed. We recommend you start by reading the perlootut
document in the latest stable release of Perl, rather than this
version.
=end original
もし将来これを読んでいる場合、最新版は変更されている可能性があります。
このバージョンではなく、Perl の最新安定リリースの perlootut 文書を
読むことから始めることを勧めます。
=head1 DESCRIPTION
=begin original
This document provides an introduction to object-oriented programming
in Perl. It begins with a brief overview of the concepts behind object
oriented design. Then it introduces several different OO systems from
L<CPAN|http://search.cpan.org> which build on top of what Perl
provides.
=end original
この文書は Perl でのオブジェクト指向プログラミングを紹介します。
これはオブジェクト指向設計の背後にあるコンセプトの概説から始めます。
それから Perl が提供するものの上に構築されている、
L<CPAN|http://search.cpan.org> にあるいくつかの OO システムを紹介します。
=begin original
By default, Perl's built-in OO system is very minimal, leaving you to
do most of the work. This minimalism made a lot of sense in 1994, but
in the years since Perl 5.0 we've seen a number of common patterns
emerge in Perl OO. Fortunately, Perl's flexibility has allowed a rich
ecosystem of Perl OO systems to flourish.
=end original
デフォルトでは、Perl の組み込みの OO システムはとても最小限です; ほとんどの
作業を自分でする必要があります。
この最小限主義は 1994 年には十分意味のあるものでしたが、Perl 5.0 から
時が経つにつれて、Perl OO に多くの共通のパターンが見られるようになりました。
幸い、Perl の柔軟性により、Perl OO システムの豊かなエコシステムが
発展しました。
=begin original
If you want to know how Perl OO works under the hood, the L<perlobj>
document explains the nitty gritty details.
=end original
裏で Perl OO がどのように動作するのかを知りたい場合は、L<perlobj> 文書が
本質的な詳細について説明しています。
=begin original
This document assumes that you already understand the basics of Perl
syntax, variable types, operators, and subroutine calls. If you don't
understand these concepts yet, please read L<perlintro> first. You
should also read the L<perlsyn>, L<perlop>, and L<perlsub> documents.
=end original
この文書は、Perl の文法、変数型、演算子、サブルーチン呼び出しの基本について
既に理解していると仮定しています。
まだこれらのコンセプトについてまだ理解していないなら、まず L<perlintro> を
読んでください。
L<perlsyn>, L<perlop>, L<perlsub> 文書も読むべきでしょう。
=head1 OBJECT-ORIENTED FUNDAMENTALS
(オブジェクト指向の基本)
=begin original
Most object systems share a number of common concepts. You've probably
heard terms like "class", "object, "method", and "attribute" before.
Understanding the concepts will make it much easier to read and write
object-oriented code. If you're already familiar with these terms, you
should still skim this section, since it explains each concept in terms
of Perl's OO implementation.
=end original
ほとんどのオブジェクトシステムは多くの共通の概念を共有しています。
おそらく以前に「クラス」、「オブジェクト」、「メソッド」、属性といった
用語について聞いたことがあるでしょう。
概念の理解は、オブジェクト指向のコードを読み書きするよりも遥かに容易です。
既にこれらの用語に親しんでいても、この章に目を通すべきです; なぜなら
Perl の OO 実装の用語でそれぞれの概念を説明しているからです。
=begin original
Perl's OO system is class-based. Class-based OO is fairly common. It's
used by Java, C++, C#, Python, Ruby, and many other languages. There
are other object orientation paradigms as well. JavaScript is the most
popular language to use another paradigm. JavaScript's OO system is
prototype-based.
=end original
Perl の OO システムはクラスベースです。
クラスベース OO はかなり一般的です。
これは Java, C++, C#, Python, Ruby およびその他の多くの言語で使われています。
その他のオブジェクト指向パラダイムもあります。
JavaScript は、その他のパラダイムを使っている最も有名な言語です。
JavaScript の OO システムはプロトタイプベースです。
=head2 Object
(オブジェクト)
=begin original
An B<object> is a data structure that bundles together data and
subroutines which operate on that data. An object's data is called
B<attributes>, and its subroutines are called B<methods>. An object can
be thought of as a noun (a person, a web service, a computer).
=end original
B<オブジェクト> は、データと、そのデータを操作するサブルーチンを一つに
まとめたデータ構造です。
オブジェクトのデータは B<属性> と呼ばれ、サブルーチンは B<メソッド> と
呼ばれます。
オブジェクトは名詞と考えることができます (人、web サービス、
コンピュータなど)。
=begin original
An object represents a single discrete thing. For example, an object
might represent a file. The attributes for a file object might include
its path, content, and last modification time. If we created an object
to represent F</etc/hostname> on a machine named "foo.example.com",
that object's path would be "/etc/hostname", its content would be
"foo\n", and it's last modification time would be 1304974868 seconds
since the beginning of the epoch.
=end original
オブジェクトは単一のものを表現します。
たとえば、あるオブジェクトがファイルを表現しているとします。
ファイルオブジェクトの属性はパス、内容、最終更新時刻といったものになります。
オブジェクトのパスが "/etc/hostname" になるような、
"foo.example.com" という名前のマシンの F</etc/hostname> を表現する
オブジェクトを作る場合、その内容は "foo\n" で、最終更新時刻は紀元から
1304974868 秒といったものになります。
=begin original
The methods associated with a file might include C<rename()> and
C<write()>.
=end original
ファイルに結びつけられたメソッドは C<rename()> や C<write()> と
いったものになります。
=begin original
In Perl most objects are hashes, but the OO systems we recommend keep
you from having to worry about this. In practice, it's best to consider
an object's internal data structure opaque.
=end original
Perl ではほとんどのオブジェクトはハッシュですが、推奨する OO システムは
これについて気にする必要がないようにします。
実際には、オブジェクトの内部構造は不透明であると考えるのが最良です。
=head2 Class
(クラス)
=begin original
A B<class> defines the behavior of a category of objects. A class is a
name for a category (like "File"), and a class also defines the
behavior of objects in that category.
=end original
B<クラス> はあるカテゴリのオブジェクトの振る舞いを定義します。
クラスは("File" のような)カテゴリを表す名前です; またクラスは
そのカテゴリのオブジェクトの振る舞いを定義します。
=begin original
All objects belong to a specific class. For example, our
F</etc/hostname> object belongs to the C<File> class. When we want to
create a specific object, we start with its class, and B<construct> or
B<instantiate> an object. A specific object is often referred to as an
B<instance> of a class.
=end original
全てのオブジェクトは何らかのクラスに属します。
例えば、F</etc/hostname> オブジェクトは C<File> クラスに属します。
特定のオブジェクトを作りたい場合、そのクラスから始めて、オブジェクトを
B<構築>(construct) または B<インスタンス化> (instantiate) します。
特定のオブジェクトはしばしばクラスの B<インスタンス> (instance) と
呼ばれます。
=begin original
In Perl, any package can be a class. The difference between a package
which is a class and one which isn't is based on how the package is
used. Here's our "class declaration" for the C<File> class:
=end original
Perl では、どのパッケージもクラスになれます。
クラスであるパッケージとそうでないパッケージの違いは、パッケージがどのように
使われるかによります。
以下は C<File> クラスのための「クラス宣言」です:
package File;
=begin original
In Perl, there is no special keyword for constructing an object.
However, most OO modules on CPAN use a method named C<new()> to
construct a new object:
=end original
Perl では、オブジェクトの構築のための特別なキーワードはありません。
しかし、CPAN のほとんどの OO モジュールは、新しいオブジェクトの構築に
C<new()> という名前のメソッドを使います:
my $hostname = File->new(
path => '/etc/hostname',
content => "foo\n",
last_mod_time => 1304974868,
);
=begin original
(Don't worry about that C<< -> >> operator, it will be explained
later.)
=end original
(C<< -> >> 演算子について心配しないでください; 後で説明します。)
=head3 Blessing
(bless)
=begin original
As we said earlier, most Perl objects are hashes, but an object can be
an instance of any Perl data type (scalar, array, etc.). Turning a
plain data structure into an object is done by B<blessing> that data
structure using Perl's C<bless> function.
=end original
既に述べたように、ほとんどの Perl オブジェクトはハッシュですが、
オブジェクトはどの Perl データ型 (スカラ、配列など)のインスタンスも可能です。
普通のデータ構造のオブジェクトへの変換は、データ構造に Perl の C<bless> 関数を
使うことによる B<bless> によって行われます。
=begin original
While we strongly suggest you don't build your objects from scratch,
you should know the term B<bless>. A B<blessed> data structure (aka "a
referent") is an object. We sometimes say that an object has been
"blessed into a class".
=end original
一からオブジェクトを構築しないことを強く勧めますが、B<bless> という
用語は知っておくべきです。
B<bless された> データ構造 (またの名を「リファレンス先」)はオブジェクトです。
時々、オブジェクトは「クラスに bless された」と表現します。
=begin original
Once a referent has been blessed, the C<blessed> function from the
L<Scalar::Util> core module can tell us its class name. This subroutine
returns an object's class when passed an object, and false otherwise.
=end original
一旦リファレンス先が bless されると、L<Scalar::Util> コアモジュールの
C<blessed> 関数はそのクラス名を返します。
このサブルーチンは、オブジェクトが和されるとオブジェクトのクラスを返し、
さもなければ偽を返します。
use Scalar::Util 'blessed';
print blessed($hash); # undef
print blessed($hostname); # File
=head3 Constructor
(コンストラクタ)
=begin original
A B<constructor> creates a new object. In Perl, a class's constructor
is just another method, unlike some other languages, which provide
syntax for constructors. Most Perl classes use C<new> as the name for
their constructor:
=end original
B<コンストラクタ> は新しいオブジェクトを作成します。
コンストラクタのための文法を提供しているその他の言語と異なり、Perl では
クラスのコンストラクタは単なるメソッドです。
ほとんどの Perl クラスはコンストラクタの名前として C<new> を使います:
my $file = File->new(...);
=head2 Methods
(メソッド)
=begin original
You already learned that a B<method> is a subroutine that operates on
an object. You can think of a method as the things that an object can
I<do>. If an object is a noun, then methods are its verbs (save, print,
open).
=end original
オブジェクトを操作するサブルーチンが B<メソッド> であるということは
既に学んでいます。
メソッドはオブジェクトが I<する> ことと考えることができます。
オブジェクトが名詞なら、メソッドは動詞 (保存する、表示する、開く) です。
=begin original
In Perl, methods are simply subroutines that live in a class's package.
Methods are always written to receive the object as their first
argument:
=end original
Perl では、メソッドは単にクラスのパッケージにあるサブルーチンです。
メソッドは常に最初の引数としてオブジェクトを受け取るように書かれます:
sub print_info {
my $self = shift;
print "This file is at ", $self->path, "\n";
}
$file->print_info;
# The file is at /etc/hostname
=begin original
What makes a method special is I<how it's called>. The arrow operator
(C<< -> >>) tells Perl that we are calling a method.
=end original
メソッドを特別なものにしているのは、I<どのように呼び出されるか> です。
矢印演算子 (C<< -> >>) は、メソッドとして呼び出していることを Perl に
知らせます。
=begin original
When we make a method call, Perl arranges for the method's B<invocant>
to be passed as the first argument. B<Invocant> is a fancy name for the
thing on the left side of the arrow. The invocant can either be a class
name or an object. We can also pass additional arguments to the method:
=end original
メソッド呼び出しをするとき、Perl はメソッドの B<呼び出し元> (invocant) を
最初の引数として渡すように用意します。
to be passed as the first argument.
B<呼び出し元> とは矢印の左側にあるものの名前です。
呼び出し元はクラス名とオブジェクトのどちらかです。
また、メソッドに追加の引数も渡せます:
sub print_info {
my $self = shift;
my $prefix = shift // "This file is at ";
print $prefix, ", ", $self->path, "\n";
}
$file->print_info("The file is located at ");
# The file is located at /etc/hostname
=head2 Attributes
(属性)
=begin original
Each class can define its B<attributes>. When we instantiate an object,
we assign values to those attributes. For example, every C<File> object
has a path. Attributes are sometimes called B<properties>.
=end original
各クラスは B<属性> を定義します。
オブジェクトをインスタンス化するとき、これらの属性に値を代入します。
例えば、各 C<File> オブジェクトはパスを持ちます。
属性は時々 B<プロパティ> (properties) と呼ばれます。
=begin original
Perl has no special syntax for attributes. Under the hood, attributes
are often stored as keys in the object's underlying hash, but don't
worry about this.
=end original
Perl には属性のための特別な文法はありません。
内部では、属性はしばしばオブジェクトの基となっているハッシュのキーとして
保管されますが、これについて気にすることはありません。
=begin original
We recommend that you only access attributes via B<accessor> methods.
These are methods that can get or set the value of each attribute. We
saw this earlier in the C<print_info()> example, which calls C<<
$self->path >>.
=end original
属性には B<アクセサ> (accessor) メソッドを経由してのみアクセスすることを
勧めます。
これはそれぞれの属性の値を取得または設定するメソッドです。
既に、前述した C<print_info()> の例で、C<< $self->path >> を
呼び出しているのを見ています。
=begin original
You might also see the terms B<getter> and B<setter>. These are two
types of accessors. A getter gets the attribute's value, while a setter
sets it. Another term for a setter is B<mutator>
=end original
B<ゲッター> (getter) と B<セッター> (setter) という用語も見るかも知れません。
これらはアクセサの種類です。
ゲッターは属性の値を取得し、セッターは設定します。
セッターに関する別名は B<ミューテータ> (mutator) です。
=begin original
Attributes are typically defined as read-only or read-write. Read-only
attributes can only be set when the object is first created, while
read-write attributes can be altered at any time.
=end original
属性は典型的には読み込み専用または読み書き可能として定義されます。
読み込み専用属性はオブジェクトが最初に作成されるときにのみ設定でき、
読み書き可能属性はいつでも変更できます。
=begin original
The value of an attribute may itself be another object. For example,
instead of returning its last mod time as a number, the C<File> class
could return a L<DateTime> object representing that value.
=end original
属性の値それ自身が他のオブジェクトかも知れません。
例えば、最終更新時刻を数値として返す代わりに、C<File> クラスはその値を
表現する L<DateTime> オブジェクトを返すかも知れません。
=begin original
It's possible to have a class that does not expose any publicly
settable attributes. Not every class has attributes and methods.
=end original
設定可能な属性が一切公開されていないクラスも可能です。
全てのクラスが属性とメソッドを持っているというわけではありません。
=head2 Polymorphism
(多態性)
=begin original
B<Polymorphism> is a fancy way of saying that objects from two
different classes share an API. For example, we could have C<File> and
C<WebPage> classes which both have a C<print_content()> method. This
method might produce different output for each class, but they share a
common interface.
=end original
B<多態性> (polymorphism) は二つの異なるクラスが API を共有しているということを
示す変わった方法です。
例えば、どちらも C<print_content()> メソッドを持つ、C<File> クラスと
C<WebPage> クラスを持てます。
このメソッドはクラスごとに異なった出力を生成するかも知れませんが、共通の
インターフェースを共有します。
=begin original
While the two classes may differ in many ways, when it comes to the
C<print_content()> method, they are the same. This means that we can
try to call the C<print_content()> method on an object of either class,
and B<we don't have to know what class the object belongs to!>
=end original
二つのクラスはいろいろな意味で異なっているかも知れませんが、
C<print_content()> メソッドを呼び出すときには、これらは同じです。
これは、どちらのクラスのオブジェクトに対しても C<print_content()> を
呼び出そうとすることができて、B<オブジェクトがどのクラスに属しているかを
知る必要がないと言うことです!>
=begin original
Polymorphism is one of the key concepts of object-oriented design.
=end original
多態性はオブジェクト指向設計の鍵となる概念の一つです。
=head2 Inheritance
(継承)
=begin original
B<Inheritance> lets you create a specialized version of an existing
class. Inheritance lets the new class reuse the methods and attributes
of another class.
=end original
B<継承> は既にあるクラスの特殊版を作成できるようにします。
継承は他のクラスのメソッドと属性を再利用して新しいクラスを
作成できるようにします。
=begin original
For example, we could create an C<File::MP3> class which B<inherits>
from C<File>. An C<File::MP3> B<is-a> I<more specific> type of C<File>.
All mp3 files are files, but not all files are mp3 files.
=end original
例えば、C<File> から B<継承> した C<File::MP3> クラスを作成できます。
C<File::MP3> B<は> (is-a) C<File> の I<より特殊な> 型です。
全ての mp3 ファイルはファイルですが、全てのファイルが
mp3 ファイルというわけではありません。.
=begin original
We often refer to inheritance relationships as B<parent-child> or
C<superclass/subclass> relationships. Sometimes we say that the child
has an B<is-a> relationship with its parent class.
=end original
継承関係はしばしば B<親-子> または C<スーパークラス/サブクラス> 関係として
参照されます。
子は親クラスとの B<is-a> 関係を持つと表現することがあります。
=begin original
C<File> is a B<superclass> of C<File::MP3>, and C<File::MP3> is a
B<subclass> of C<File>.
=end original
C<File> は C<File::MP3> の B<スーパークラス> で、C<File::MP3> は C<File> の
B<サブクラス> です。
package File::MP3;
use parent 'File';
=begin original
The L<parent> module is one of several ways that Perl lets you define
inheritance relationships.
=end original
L<parent> モジュールは、Perl で継承関係を定義するいくつかの方法のひとつです。
=begin original
Perl allows multiple inheritance, which means that a class can inherit
from multiple parents. While this is possible, we strongly recommend
against it. Generally, you can use B<roles> to do everything you can do
with multiple inheritance, but in a cleaner way.
=end original
Perl は多重継承を認めています; つまり、クラスは複数の親から継承できます。
これは可能ですが、行わないように強く勧めます。
一般的に、多重継承で行えることは全て、B<ロール> を使うことでより
きれいな形で行えます。
=begin original
Note that there's nothing wrong with defining multiple subclasses of a
given class. This is both common and safe. For example, we might define
C<File::MP3::FixedBitrate> and C<File::MP3::VariableBitrate> classes to
distinguish between different types of mp3 file.
=end original
あるクラスに対して複数のサブクラスを定義することは何も悪くないことに
注意してください。
これは一般的でかつ安全です。
例えば、mp3 ファイルの異なった種類を区別するために、
C<File::MP3::FixedBitrate> クラスと C<File::MP3::VariableBitrate> クラスを
定義できます。
=head3 Overriding methods and method resolution
(メソッドのオーバーライドとメソッド解決)
=begin original
Inheritance allows two classes to share code. By default, every method
in the parent class is also available in the child. The child can
explicitly B<override> a parent's method to provide its own
implementation. For example, if we have an C<File::MP3> object, it has
the C<print_info()> method from C<File>:
=end original
継承は二つのクラスでコードを共有できるようにします。
デフォルトでは、親クラスの全てのメソッドは子でも利用可能です。
子は、独自の実装を提供することで親のメソッドを明示的に B<オーバーライド>
(override) できます。
例えば、C<File::MP3> オブジェクトがあれば、C<File> からの
C<print_info()> メソッドがあります:
my $cage = File::MP3->new(
path => 'mp3s/My-Body-Is-a-Cage.mp3',
content => $mp3_data,
last_mod_time => 1304974868,
title => 'My Body Is a Cage',
);
$cage->print_info;
# The file is at mp3s/My-Body-Is-a-Cage.mp3
=begin original
If we wanted to include the mp3's title in the greeting, we could
override the method:
=end original
返り値に mp3 のタイトルを含めたい場合、メソッドをオーバーライドできます:
package File::MP3;
use parent 'File';
sub print_info {
my $self = shift;
print "This file is at ", $self->path, "\n";
print "Its title is ", $self->title, "\n";
}
$cage->print_info;
# The file is at mp3s/My-Body-Is-a-Cage.mp3
# Its title is My Body Is a Cage
=begin original
The process of determining what method should be used is called
B<method resolution>. What Perl does is look at the object's class
first (C<File::MP3> in this case). If that class defines the method,
then that class's version of the method is called. If not, Perl looks
at each parent class in turn. For C<File::MP3>, its only parent is
C<File>. If C<File::MP3> does not define the method, but C<File> does,
then Perl calls the method in C<File>.
=end original
どのメソッドが使われるべきかを決定する処理は、B<メソッド解決>
(method resolution) と呼ばれます。
Perl が行うことは、まずオブジェクトのクラス (この場合は C<File::MP3>) を
見ます。
このクラスにメソッドが定義されていれば、そのクラスのメソッドが呼び出されます。
さもなければ、Perl は順番に親クラスを見ます。
C<File::MP3> の場合、唯一の親は C<File> です。
C<File::MP3> がメソッドを定義しておらず、C<File> が定義しているなら、
Perl は C<File> のメソッドを呼び出します。
=begin original
If C<File> inherited from C<DataSource>, which inherited from C<Thing>,
then Perl would keep looking "up the chain" if necessary.
=end original
C<File> が C<DataSource> から継承され、これが C<Thing> から継承されていれば、
Perl はもし必要なら「チェーンをたどって」探し続けます。
=begin original
It is possible to explicitly call a parent method from a child:
=end original
子から親メソッドを明示的に呼び出すことは可能です:
package File::MP3;
use parent 'File';
sub print_info {
my $self = shift;
$self->SUPER::print_info();
print "Its title is ", $self->title, "\n";
}
=begin original
The C<SUPER::> bit tells Perl to look for the C<print_info()> in the
C<File::MP3> class's inheritance chain. When it finds the parent class
that implements this method, the method is called.
=end original
C<SUPER::> は、C<File::MP3> クラスの継承チェーンから C<print_info()> を
探すように Perl に伝えます。
このメソッドを実装している親クラスが見つかると、そのメソッドが
呼び出されます。
=begin original
We mentioned multiple inheritance earlier. The main problem with
multiple inheritance is that it greatly complicates method resolution.
See L<perlobj> for more details.
=end original
以前に多重継承について述べました。
多重継承の主な問題は、メソッド解決が非常に込み入っているということです。
さらなる詳細については L<perlobj> を参照してください。
=head2 Encapsulation
(カプセル化)
=begin original
B<Encapsulation> is the idea that an object is opaque. When another
developer uses your class, they don't need to know I<how> it is
implemented, they just need to know I<what> it does.
=end original
B<カプセル化> は、オブジェクトを不透明にする考え方です。
他の開発者があなたのクラスを使うとき、I<どのように> 実装されているかを
知る必要はなく、単に I<何を> するかを知る必要があるだけです。
=begin original
Encapsulation is important for several reasons. First, it allows you to
separate the public API from the private implementation. This means you
can change that implementation without breaking the API.
=end original
カプセル化はいくつかの理由で重要です。
まず、これにより公的な API を内部の実装から分離できます。
これにより、API を壊すことなく実装を変更できます。
=begin original
Second, when classes are well encapsulated, they become easier to
subclass. Ideally, a subclass uses the same APIs to access object data
that its parent class uses. In reality, subclassing sometimes involves
violating encapsulation, but a good API can minimize the need to do
this.
=end original
次に、クラスが十分にカプセル化されていれば、サブクラス化が容易になります。
理想的には、サブクラスは親クラスが使っているオブジェクトデータに
アクセスするのに同じ API を使います。
実際には、サブクラス化は時々カプセル化に違反しますが、よい API は
その必要性を最小限にします。
=begin original
We mentioned earlier that most Perl objects are implemented as hashes
under the hood. The principle of encapsulation tells us that we should
not rely on this. Instead, we should use accessor methods to access the
data in that hash. The object systems that we recommend below all
automate the generation of accessor methods. If you use one of them,
you should never have to access the object as a hash directly.
=end original
既に、ほとんどの Perl オブジェクトは内部ではハッシュとして実装されていると
述べました。
カプセル化の原則は、このことに依存するべきではないと伝えています。
代わりに、ハッシュのデータにアクセスするためにアクセサメソッドを使います。
後に推奨するオブジェクトシステムは全てアクセサメソッドの生成を自動化します。
これらの一つを使うなら、オブジェクトをハッシュとして直接アクセスする必要は
ないはずです。
=head2 Composition
(包含)
=begin original
In object-oriented code, we often find that one object references
another object. This is called B<composition>, or a B<has-a>
relationship.
=end original
オブジェクト指向のコードでは、しばしばあるオブジェクトが他のオブジェクトを
参照しています。
これは B<包含> (composition)、または B<has-a> 関係と呼ばれます。
=begin original
Earlier, we mentioned that the C<File> class's C<last_mod_time>
accessor could return a L<DateTime> object. This is a perfect example
of composition. We could go even further, and make the C<path> and
C<content> accessors return objects as well. The C<File> class would
then be B<composed> of several other objects.
=end original
既に、C<File> クラスの C<last_mod_time> アクセサが L<DateTime> オブジェクトを
返すかも知れないことに触れました。
これは包含の完璧な例です。
さらに進めて、C<path> と C<content> アクセサもオブジェクトを返すようにも
できます。
そして C<File> クラスはいくつかのその他のオブジェクトの B<包含> になります。
=head2 Roles
(ロール)
=begin original
B<Roles> are something that a class I<does>, rather than something that
it I<is>. Roles are relatively new to Perl, but have become rather
popular. Roles are B<applied> to classes. Sometimes we say that classes
B<consume> roles.
=end original
B<ロール> は、クラスが I<何か> ではなく、クラスが I<何をするか> です。
ロールは Perl では比較的新しいですが、かなり人気になってきています。
ロールはクラスに B<適用> されます。
クラスがロールを B<消費> (consume) するということもあります。
=begin original
Roles are an alternative to inheritance for providing polymorphism.
Let's assume we have two classes, C<Radio> and C<Computer>. Both of
these things have on/off switches. We want to model that in our class
definitions.
=end original
ロールは多態性を提供するための継承の代替策です。
二つのクラス C<Radio> と C<Computer> があると考えます。
どちらもオン/オフするスイッチがあります。
これをクラス定義でモデル化したいとします。
=begin original
We could have both classes inherit from a common parent, like
C<Machine>, but not all machines have on/off switches. We could create
a parent class called C<HasOnOffSwitch>, but that is very artificial.
Radios and computers are not specializations of this parent. This
parent is really a rather ridiculous creation.
=end original
C<Machine> のように、共通の親から両方のクラスを継承することもできますが、
全ての機械にオン/オフスイッチがあるわけではありません。
C<HasOnOffSwitch> と呼ばれる親クラスを作ることもできますが、とても
不自然です。
ラジオとコンピュータはこの親の特殊化ではありません。
この親は実際にはかなりおかしなものです。
=begin original
This is where roles come in. It makes a lot of sense to create a
C<HasOnOffSwitch> role and apply it to both classes. This role would
define a known API like providing C<turn_on()> and C<turn_off()>
methods.
=end original
これはロールの出番です。
C<HasOnOffSwitch> ロールを作って両方のクラスに適用することは
とても合理的です。
このロールは C<turn_on()> と C<turn_off()> メソッドを提供するような
既知の API を定義します。
=begin original
Perl does not have any built-in way to express roles. In the past,
people just bit the bullet and used multiple inheritance. Nowadays,
there are several good choices on CPAN for using roles.
=end original
Perl にはロールを記述する組み込みの方法はありません。
以前は、人々は我慢して多重継承を使っていました。
最近は、ロールを使うためのいくつかの良い選択肢が CPAN にあります。
=head2 When to Use OO
(いつ OO を使うか)
=begin original
Object Orientation is not the best solution to every problem. In I<Perl
Best Practices> (copyright 2004, Published by O'Reilly Media, Inc.),
Damian Conway provides a list of criteria to use when deciding if OO is
the right fit for your problem:
=end original
オブジェクト指向は全ての問題に対する最良の解法というわけではありません。
I<Perl Best Practices> (copyright 2004, Published by O'Reilly Media, Inc.)
において、Damian Conway は OO が問題に正しく適応するかどうかを決定するときに
使う基準の一覧を提供しています:
=over 4
=item *
=begin original
The system being designed is large, or is likely to become large.
=end original
設計しているシステムが大きいか、大きくなりそう。
=item *
=begin original
The data can be aggregated into obvious structures, especially if
there's a large amount of data in each aggregate.
=end original
データが明らかな構造に集合できる; 特にそれぞれの集合が大量のデータを持つ。
=item *
=begin original
The various types of data aggregate form a natural hierarchy that