你會在因能見度某些時候需要反思。如果你能夠預先接受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