从单例模式继承

时间:2017-09-18 02:52:07

标签: java oop

当我试图继承一个接着是Singleton Pattern的类时,我遇到了问题。 假设有一个类,称为P,后跟Singleton Pattern并实现一个称为I_able的接口。

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必须是程序中唯一的对象。 有什么建议吗?

1 个答案:

答案 0 :(得分:1)

您的代码中的问题是您的父类P.

中定义了static I_able instance

因此,当您在课程getInstanceAB时,他们都会引用其父级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()