You will need Reflection at some point due to visibility. If you can take Reflection once in advance and not use it again, that would probably be ideal, right?
You can put the getInstance() method on a hidden interface (located in the same package as IMyClass , MyClassImpl and A , but not ClientOfA ), and then pass the prototype MyClassImpl to A.init() .
// -- You wish you would have thought of the word prototypeable! ...maybe? interface IMyClassPrototypeable extends IMyClass { public IMyClass getInstance(); } class MyClassImpl implements IMyClassPrototypeable // -- and IMyClass by extension. { // -- Still not visible outside this package. public IMyClass getInstance() { return new MyClassImpl(); } } class A { private IMyClassPrototypeable prototype; // -- This method is package-private. void init( IMyClassPrototypeable prototype ) { this.prototype = prototype; } public IMyClass createMyClass() { return prototype.getInstance(); } }
This solution would require Reflection to create an instance of the MyClassImpl prototype that could be executed using Spring (or some other form of dependency injection). It uses the Prototype pattern, the Factory -method pattern, and easily supports the Singleton / Pool pattern, but remember that more design patterns used are not always better. In fact, this can make design (and code) more complex and difficult for beginners to understand.
For the record, the only reason I would even think of this solution is because it takes a hit of reflection once, in front, and not every time createMyClass() is createMyClass() , on which the original poster indicated that he / she will be often.
source share