Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从单例模式继承_Java_Oop - Fatal编程技术网

Java 从单例模式继承

Java 从单例模式继承,java,oop,Java,Oop,我在尝试继承一个后跟单例模式的类时遇到了一个问题。 假设有一个名为P的类,后跟Singleton模式,并实现一个名为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 illeg

我在尝试继承一个后跟单例模式的类时遇到了一个问题。 假设有一个名为P的类,后跟Singleton模式,并实现一个名为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
问题是为什么A中的实例和B中的实例是同一个对象。 事实上,我有点知道这是为什么,但我想知道我如何才能解决这个问题。 A和B必须是程序中唯一的对象。
有什么建议吗?

代码中的问题是您的
静态可访问实例
是在父类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()

也许这篇文章会帮助你理解这种行为。
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()