9.4 How to Build a Horse
If you constructed all your horses by hand, you'd
most likely make mistakes from time to time. Making the
"inside guts" of a
Horse visible also violates one of the principles
of OOP. That's good if you're a
veterinarian but not if you just like to own horses. Let the
Horse class build a new horse:
{ package Horse;
@ISA = qw(Animal);
sub sound { "neigh" }
sub name {
my $self = shift;
$$self;
}
sub named {
my $class = shift;
my $name = shift;
bless \$name, $class;
}
}
Now with the new named method, build a
Horse:
my $tv_horse = Horse->named("Mr. Ed");
You're
back to a class method, so the two arguments to
Horse::named are "Horse" and
"Mr. Ed". The bless operator
not only blesses $name, it also returns the
reference to $name, so that's
fine as a return value. And that's how to build a
horse.
You called the constructor
named here so it quickly denotes the
constructor's argument as the name for this
particular Horse. You can use different
constructors with different names for different ways of
"giving birth" to the object (such
as recording its pedigree or date of birth). However,
you'll find that most people coming to Perl from
less-flexible languages (such as Java or C++) use
a single constructor named new, with various ways
of interpreting the arguments to new. Either style
is fine, as long as you document your particular way of giving birth
to an object. Most core and CPAN modules use new,
with notable exceptions, such as DBI's
DBI->connect( ). It's really
up to the author. It all works, as long as it's
documented.
|