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 automatic object building, I do not get to understand if this something possible, and how to create a Moose class with Moose syntax and having this behaviour.
e.g.:
The user asks: $file = Repository->new(uri=>'sftp://blabla') …. and is returned an `Repository::_Sftp“ instance
User would use $file as if it is a Repository instance, without the need to know the real subclass (polymorphism)
Note:
As requested, maybe i should have been more clear about what i was trying to achieve:
The purpose of my class is to be able to add new Repository schemes (eg over sftp), by simply creating an “hidden” Repository::_Stfp class, and adding a case in the Repository constructor to factory the correct specialized object depending of url. Repository would be like a virtual base class, providing an interface that specialized objects would implement.
All of this is for adding new repository schemes without having the rest of the program to be modified: it would unknowingly deal with the specialized instance as if it is a Repository instance.
newbuilds the builder. You want some other method to actually return the built object.Here’s an example:
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
Repositoryrole does. (You will want to add theAPI 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:
But if you do:
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
doesinstead ofisa:And you’re done.