我在尝试继承一个遵循单例模式并实现了接口I_able的类P时遇到了问题。
abstract class P implement I_able {
static protected I_able instance = null;
protected object member1;
// abstract static I_able getInstance(); <-- this is an illegal declaration.
abstract public void method1() ;
} // class P
现在,有两个类想要从P继承,如下所示。
class A inheritance P {
static public I_able getInstance() {
if ( instance == null )
instance = new A() ;
return (A) instance ;
} // getInstance()
override public void method1() {
...
} // method1()
} // A()
class B inheritance P {
static public I_able getInstance() {
if ( instance == null )
instance = new B() ;
return (B) instance ;
} // getInstance()
override public void method1() {
...
} // method1()
} // B()
问题是为什么A中的实例和B中的实例是同一个对象。实际上,我有点知道为什么,但我想知道如何修复它。在程序中,A和B必须是唯一的对象。有什么建议吗?