I'm reading Programming Perl
, and I found this code snippet:
sub new {
my $invocant = shift;
my $class = ref($invocant) || $invocant;
my $self = {
color => "bay",
legs => 4,
owner => undef,
@_, # Override previous attributes
};
return bless $self, $class;
}
With constructors like this one, what's the benefit of calling new
on an object instance? I assume that it's what it's for, right? My guess is that if anyone would want to write such a constructor, he would have to add some more code that copies the attributes of the first object to the one about to be created.
So you can construct another object of the same class without knowing what the original class's object is - this can make for some really neat compact factory pattern.
As an example, this is useful when you have resource objects you need to construct, as need arises and the cost of computing WHICH kind of resource object is high (say, a long-running DB query). Therefore, a factory would see if it was passed an old resource object and if so, create one just like it by merely calling $old_object->new()
- avoiding the resource cost of re-computing the kind of resource.
As another example, if you have class hierarchy denoting animals, and a factory for constructing new animals in a simulation, you could call $newborn = $factory->make_new_animal($mother)
with the factory implementation being merely $object->new()