Hi! So I have this copy of "Effective Java" and right at the beginning there is the description of a static builder class.
Say you have a class that has many parameters, and most of them are optional parameters. So making several constructors with all the different combinations of parameters becomes a lot of work.
Instead you make a single private constructor with all the parameters and a static nested class (a "builder" ) that has methods for setting up each parameter and a build method that constructs a new instance of the object once you have set up the parameters you want.
It would be something like this:
I've implemented this with my Mesh class. Since it has many parameters and several configurations (normals, no normals, indexed, non indexed, etc).
So for instancing a Mesh object i'd call
Mesh lamp = new Mesh.Builder([mandatory parameters]).indices(lampIndices).normals(lampNormals).build()
and I'd get an indexed lamp model with normals without calling the constructor with 15 or so parameters. Each Builder method returns the builder itself so you can "concatenate" method callings.
This is all and great until I need more specific functionality out of my mesh objects. I wanted to implement conventional character movement (ie, not a floating camera) and for that I need to retrieve positions from the ground. For that I'd need to add some methods to the object that holds my terrain data, say, a new MeshTerrain class that inherits from Mesh.
It seems that the static factory wouldn't allow me to subclass Mesh at all, given the private constructor. And even then I'm not sure how that would work, could MeshTerrain use Mesh static builder?
And I have another question. I don't understand exactly the business with the nested static class.
For example, by making the call "new Mesh.Builder()" what I am exactly instantiating there? A Builder object? How that could be if its an static class? How the static Builder class can have a constructor? Or am I instantiating an enclosing Mesh object? But then, wouldn't that mean I'm instantiating two Mesh objects since I call "new Mesh" in the build() method?