继承单例模式

3

我在尝试继承一个遵循单例模式并实现了接口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必须是唯一的对象。有什么建议吗?

也许这篇文章可以帮助你理解这种行为。https://dev59.com/xHE85IYBdhLWcg3wdDEM - Cata
1个回答

1
您的代码问题在于您的static I_able instance被定义在父类P中。因此,当您在类A和B中调用getInstance时,它们都会引用其父类P的静态变量instance
我不确定您希望函数如何执行,但建议在每个子类中实现Singleton模式进行修改。
class A inheritance P {
    static protected I_able AInstance = null; 

    static public I_able getInstance() {
        if ( AInstance == null ) 
             AInstance = new A() ;
        return (A) AInstance ;
    } // getInstance()

    override public void method1() {
        ...
    } // method1() 
} // A()

class B inheritance P {
    static protected I_able BInstance = null; 

    static public I_able getInstance() {
        if ( BInstance == null ) 
            BInstance = new B() ;
        return (B) BInstance ;
    } // getInstance()

    override public void method1() {
        ...
    } // method1() 
} // B()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接