你会在因能见度某些时候需要反思。如果你能够预先接受Reflection并且不必再次使用它,那可能是理想的,是的?
你可以把一个隐藏式的接口(位于同一个包IMyClass
,MyClassImpl
和A
,但不ClientOfA
)上getInstance()
方法,然后通过一个原型的MyClassImpl
到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();
}
}
该解决方案将需要思考创造MyClassImpl
原型实例,它可以通过Spring来完成(或者依赖注入一些其他形式)。它使用Prototype模式,Factory方法模式,并且很容易支持Singleton/Pool模式,但请记住,使用的更多设计模式并不总是更好。事实上,它可以使设计(和代码)更复杂,更难以让初学者理解。
为了记录,我甚至会考虑提倡这种解决方案的唯一原因是因为它需要一次反射,而不是每次调用createMyClass()
,原始海报表明他/她会做的经常。
您可能想要注意您的编码约定是非标准的。我用于接口声明和方法上限通常不在Java中使用。 (有些人会争论接口之一,但Eclipse是我见过的唯一主要代码)。 – Robin 2011-05-27 18:58:14