I want to create a generic class, whose builder would not return an instance of this generic class, but an instance of a dedicated child class.
As Moose does automat
new
builds the builder. You want some other method to actually return the built object.
Here's an example:
class RepositoryBuilder {
has 'allow_network_repositories' => (
is => 'ro',
isa => 'Bool',
required => 1,
);
method build_repository(Uri $url) {
confess 'network access is not allowed'
if $url->is_network_url && !$self->allow_network_repositories;
my $class = $self->determine_class_for($url); # Repository::Whatever
return $class->new( url => $url );
}
}
role Repository {
Here, the builder and the built object are distinct. The builder is a real object, complete with parameters, that can be customized to build objects as the situation demands. Then, the "built" objects are merely return values of a method. This allows you to build other builders depending on the situation. (A problem with builder functions is that they are very inflexible -- it's hard to teach them a new special case. This problem still exists with a builder object, but at least your application can create a subclass, instantiate it, and pass this object to anything that needs to create objects. But dependency injection is a better approach in this case.)
Also, there is no need for the repositories you build to inherit from
anything, they just need a tag indicating that they are repositories.
And that's what our Repository
role does. (You will want to add the
API code here, and any methods that should be reused. But be careful
about forcing reuse -- are you sure everything tagged with the
Repository role will want that code? If not, just put the code in
another role and apply that one to the classes that require that
functionality.)
Here's how we use the builder we created. If, say, you don't want to touch the network:
my $b = RepositoryBuilder->new( allow_network_repositories => 0 );
$b->build_repository( 'http://google.com/' ); # error
$b->build_repository( 'file:///home/whatever' ); # returns a Repository::Foo
But if you do:
my $b = RepositoryBuilder->new( allow_network_repositories => 1 );
$b->build_repository( 'http://google.com/' ); # Repository::HTTP
Now that you have a builder that builds the objects the way you like,
you just need to use these objects in other code. So the last piece
in the puzzle is referring to "any" type of Repository object in other
code. That's simple, you use does
instead of isa
:
class SomethingThatHasARepository {
has 'repository' => (
is => 'ro',
does => 'Repository',
required => 1,
);
}
And you're done.