Re: Constructor Conundrum



"PetriSchmitz" <PetriSchmitz@xxxxxxxxxxx> wrote in
news:1135801606.900128.258410@xxxxxxxxxxxxxxxxxxxxxxxxxxxx:

> Hi Lash,
>
> I suggest to use a factory method:
>
> public class ConcreteProblem extends AbstractProblem {
> //ConcreteSolver _cs = new ConcreteSolver(); // obsolent,
> see
> factory-meth.
>
> public ConcreteProblem(ConcreteSolver _cs) { // perhabs
> change to
> private
> super(_cs);
> _cs.setParam(/* ... */);
> }
>
> public static ConcreteProblem getInstance () {
> ConcreteSolver _cs = new ConcreteSolver();
> return new ConcreteProblem (_cs);
> }
> }

The only consequence I see of the above version, compared to my original
version, is that now, instead of saying

ConcreteProblem cp = new ConcreteProblem();

I say

ConcreteProblem cp = ConcreteProblem.getInstance();

..

I toyed with factory methods a little more, but can't figure out a way to
get an abstract superclass' constructor to use its concrete subclass'
factory method, while at the same time keeping things private. Maybe it
could be done via reflection, but so too could a child's sandcastle be
sieged with a full-sized trebuchet. :)

> So you have encapsulated the constructor and seperated the creation of
> ConcreteSolver from the creation of ConcreteProblem.

I'm not sure what you mean. In the version above, ConcreteProblem cannot
be instantiated without instantiating a ConcreteSolver, so their creation
seems very much not separate.

Anyway, I settled on tighter packaging and using "protected". I'm not
100% happy with the solution, but it's the best balance of simplicity and
security I could come up with. (Plus, the project is now better
organized.)
.